blob: 939563805a9ecc87c632dd7f483a1654b5564f7c [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
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
53#ifdef __MINGW32__
54# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
55# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
56# endif
57# ifndef RIGHTMOST_BUTTON_PRESSED
58# define RIGHTMOST_BUTTON_PRESSED 0x0002
59# endif
60# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
61# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
62# endif
63# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
64# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
65# endif
66# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
67# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
68# endif
69
70/*
71 * EventFlags
72 */
73# ifndef MOUSE_MOVED
74# define MOUSE_MOVED 0x0001
75# endif
76# ifndef DOUBLE_CLICK
77# define DOUBLE_CLICK 0x0002
78# endif
79#endif
80
81/* Record all output and all keyboard & mouse input */
82/* #define MCH_WRITE_DUMP */
83
84#ifdef MCH_WRITE_DUMP
85FILE* fdDump = NULL;
86#endif
87
88/*
89 * When generating prototypes for Win32 on Unix, these lines make the syntax
90 * errors disappear. They do not need to be correct.
91 */
92#ifdef PROTO
93#define WINAPI
94#define WINBASEAPI
95typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000096typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000097typedef int ACCESS_MASK;
98typedef int BOOL;
99typedef int COLORREF;
100typedef int CONSOLE_CURSOR_INFO;
101typedef int COORD;
102typedef int DWORD;
103typedef int HANDLE;
104typedef int HDC;
105typedef int HFONT;
106typedef int HICON;
107typedef int HINSTANCE;
108typedef int HWND;
109typedef int INPUT_RECORD;
110typedef int KEY_EVENT_RECORD;
111typedef int LOGFONT;
112typedef int LPBOOL;
113typedef int LPCTSTR;
114typedef int LPDWORD;
115typedef int LPSTR;
116typedef int LPTSTR;
117typedef int LPVOID;
118typedef int MOUSE_EVENT_RECORD;
119typedef int PACL;
120typedef int PDWORD;
121typedef int PHANDLE;
122typedef int PRINTDLG;
123typedef int PSECURITY_DESCRIPTOR;
124typedef int PSID;
125typedef int SECURITY_INFORMATION;
126typedef int SHORT;
127typedef int SMALL_RECT;
128typedef int TEXTMETRIC;
129typedef int TOKEN_INFORMATION_CLASS;
130typedef int TRUSTEE;
131typedef int WORD;
132typedef int WCHAR;
133typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100134typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200135typedef int SE_OBJECT_TYPE;
136typedef int PSNSECINFO;
137typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100138typedef int STARTUPINFO;
139typedef int PROCESS_INFORMATION;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000140#endif
141
142#ifndef FEAT_GUI_W32
143/* Undocumented API in kernel32.dll needed to work around dead key bug in
144 * console-mode applications in NT 4.0. If you switch keyboard layouts
145 * in a console app to a layout that includes dead keys and then hit a
146 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
147 * and Michael Dietrich for helping me figure out this workaround.
148 */
149
150/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
151#ifndef WINBASEAPI
152# define WINBASEAPI __stdcall
153#endif
154#if defined(__BORLANDC__)
155typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
156#else
157typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
158#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000159static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160#endif
161
162#if defined(__BORLANDC__)
163/* Strangely Borland uses a non-standard name. */
164# define wcsicmp(a, b) wcscmpi((a), (b))
165#endif
166
Bram Moolenaar82881492012-11-20 16:53:39 +0100167#ifndef PROTO
168
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200169/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200170#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100171LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200172BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
173BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
174BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
175#endif
176
Bram Moolenaar82881492012-11-20 16:53:39 +0100177#endif /* PROTO */
178
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179#ifndef FEAT_GUI_W32
180/* Win32 Console handles for input and output */
181static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
182static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
183
184/* Win32 Screen buffer,coordinate,console I/O information */
185static SMALL_RECT g_srScrollRegion;
186static COORD g_coord; /* 0-based, but external coords are 1-based */
187
188/* The attribute of the screen when the editor was started */
189static WORD g_attrDefault = 7; /* lightgray text on black background */
190static WORD g_attrCurrent;
191
192static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
193static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
194static int g_fForceExit = FALSE; /* set when forcefully exiting */
195
196static void termcap_mode_start(void);
197static void termcap_mode_end(void);
198static void clear_chars(COORD coord, DWORD n);
199static void clear_screen(void);
200static void clear_to_end_of_display(void);
201static void clear_to_end_of_line(void);
202static void scroll(unsigned cLines);
203static void set_scroll_region(unsigned left, unsigned top,
204 unsigned right, unsigned bottom);
205static void insert_lines(unsigned cLines);
206static void delete_lines(unsigned cLines);
207static void gotoxy(unsigned x, unsigned y);
208static void normvideo(void);
209static void textattr(WORD wAttr);
210static void textcolor(WORD wAttr);
211static void textbackground(WORD wAttr);
212static void standout(void);
213static void standend(void);
214static void visual_bell(void);
215static void cursor_visible(BOOL fVisible);
216static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
217static char_u tgetch(int *pmodifiers, char_u *pch2);
218static void create_conin(void);
219static int s_cursor_visible = TRUE;
220static int did_create_conin = FALSE;
221#else
222static int s_dont_use_vimrun = TRUE;
223static int need_vimrun_warning = FALSE;
224static char *vimrun_path = "vimrun ";
225#endif
226
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200227static int win32_getattrs(char_u *name);
228static int win32_setattrs(char_u *name, int attrs);
229static int win32_set_archive(char_u *name);
230
Bram Moolenaar071d4272004-06-13 20:20:40 +0000231#ifndef FEAT_GUI_W32
232static int suppress_winsize = 1; /* don't fiddle with console */
233#endif
234
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200235static char_u *exe_path = NULL;
236
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100237static BOOL win8_or_later = FALSE;
238
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100239/*
240 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100241 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100242 */
243 static BOOL
244read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100245 HANDLE hInput,
246 INPUT_RECORD *lpBuffer,
247 DWORD nLength,
248 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100249{
250 enum
251 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100252 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100253 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100254 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100255 static DWORD s_dwIndex = 0;
256 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100257 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100258 int head;
259 int tail;
260 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100261
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100262 if (!win8_or_later)
263 {
264 if (nLength == -1)
265 return PeekConsoleInput(hInput, lpBuffer, 1, lpEvents);
266 return ReadConsoleInput(hInput, lpBuffer, 1, &dwEvents);
267 }
268
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100269 if (s_dwMax == 0)
270 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100271 if (nLength == -1)
272 return PeekConsoleInput(hInput, lpBuffer, 1, lpEvents);
273 if (!ReadConsoleInput(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100274 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100275 s_dwIndex = 0;
276 s_dwMax = dwEvents;
277 if (dwEvents == 0)
278 {
279 *lpEvents = 0;
280 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100281 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100282
283 if (s_dwMax > 1)
284 {
285 head = 0;
286 tail = s_dwMax - 1;
287 while (head != tail)
288 {
289 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
290 && s_irCache[head + 1].EventType
291 == WINDOW_BUFFER_SIZE_EVENT)
292 {
293 /* Remove duplicate event to avoid flicker. */
294 for (i = head; i < tail; ++i)
295 s_irCache[i] = s_irCache[i + 1];
296 --tail;
297 continue;
298 }
299 head++;
300 }
301 s_dwMax = tail + 1;
302 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100303 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100304
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100305 *lpBuffer = s_irCache[s_dwIndex];
306 if (nLength != -1 && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100307 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100308 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100309 return TRUE;
310}
311
312/*
313 * Version of PeekConsoleInput() that works with IME.
314 */
315 static BOOL
316peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100317 HANDLE hInput,
318 INPUT_RECORD *lpBuffer,
319 DWORD nLength,
320 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100321{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100322 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100323}
324
Bram Moolenaar071d4272004-06-13 20:20:40 +0000325 static void
326get_exe_name(void)
327{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100328 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
329 * as the maximum length that works (plus a NUL byte). */
330#define MAX_ENV_PATH_LEN 8192
331 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200332 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000333
334 if (exe_name == NULL)
335 {
336 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100337 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000338 if (*temp != NUL)
339 exe_name = FullName_save((char_u *)temp, FALSE);
340 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000341
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200342 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000343 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200344 exe_path = vim_strnsave(exe_name,
345 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200346 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000347 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200348 /* Append our starting directory to $PATH, so that when doing
349 * "!xxd" it's found in our starting directory. Needed because
350 * SearchPath() also looks there. */
351 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100352 if (p == NULL
353 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200354 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100355 if (p == NULL || *p == NUL)
356 temp[0] = NUL;
357 else
358 {
359 STRCPY(temp, p);
360 STRCAT(temp, ";");
361 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200362 STRCAT(temp, exe_path);
363 vim_setenv((char_u *)"PATH", temp);
364 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000365 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000366 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000367}
368
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200369/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100370 * Unescape characters in "p" that appear in "escaped".
371 */
372 static void
373unescape_shellxquote(char_u *p, char_u *escaped)
374{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100375 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100376 int n;
377
378 while (*p != NUL)
379 {
380 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
381 mch_memmove(p, p + 1, l--);
382#ifdef FEAT_MBYTE
383 n = (*mb_ptr2len)(p);
384#else
385 n = 1;
386#endif
387 p += n;
388 l -= n;
389 }
390}
391
392/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200393 * Load library "name".
394 */
395 HINSTANCE
396vimLoadLib(char *name)
397{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200398 HINSTANCE dll = NULL;
399 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200400
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200401 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
402 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200403 if (exe_path == NULL)
404 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200405 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200406 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200407#ifdef FEAT_MBYTE
408 WCHAR old_dirw[MAXPATHL];
409
410 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
411 {
412 /* Change directory to where the executable is, both to make
413 * sure we find a .dll there and to avoid looking for a .dll
414 * in the current directory. */
415 SetCurrentDirectory(exe_path);
416 dll = LoadLibrary(name);
417 SetCurrentDirectoryW(old_dirw);
418 return dll;
419 }
420 /* Retry with non-wide function (for Windows 98). */
421 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
422#endif
423 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
424 {
425 /* Change directory to where the executable is, both to make
426 * sure we find a .dll there and to avoid looking for a .dll
427 * in the current directory. */
428 SetCurrentDirectory(exe_path);
429 dll = LoadLibrary(name);
430 SetCurrentDirectory(old_dir);
431 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200432 }
433 return dll;
434}
435
Bram Moolenaar071d4272004-06-13 20:20:40 +0000436#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
437# ifndef GETTEXT_DLL
438# define GETTEXT_DLL "libintl.dll"
439# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200440/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000441static char *null_libintl_gettext(const char *);
442static char *null_libintl_textdomain(const char *);
443static char *null_libintl_bindtextdomain(const char *, const char *);
444static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000445
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200446static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000447char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
448char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
449char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000450 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000451char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
452 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000453
454 int
455dyn_libintl_init(char *libname)
456{
457 int i;
458 static struct
459 {
460 char *name;
461 FARPROC *ptr;
462 } libintl_entry[] =
463 {
464 {"gettext", (FARPROC*)&dyn_libintl_gettext},
465 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
466 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
467 {NULL, NULL}
468 };
469
470 /* No need to initialize twice. */
471 if (hLibintlDLL)
472 return 1;
473 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200474 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475 if (!hLibintlDLL)
476 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200477 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479 verbose_enter();
480 EMSG2(_(e_loadlib), GETTEXT_DLL);
481 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000482 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200483 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484 }
485 for (i = 0; libintl_entry[i].name != NULL
486 && libintl_entry[i].ptr != NULL; ++i)
487 {
488 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
489 libintl_entry[i].name)) == NULL)
490 {
491 dyn_libintl_end();
492 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000493 {
494 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000495 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000496 verbose_leave();
497 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498 return 0;
499 }
500 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000501
502 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000503 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000504 "bind_textdomain_codeset");
505 if (dyn_libintl_bind_textdomain_codeset == NULL)
506 dyn_libintl_bind_textdomain_codeset =
507 null_libintl_bind_textdomain_codeset;
508
Bram Moolenaar071d4272004-06-13 20:20:40 +0000509 return 1;
510}
511
512 void
513dyn_libintl_end()
514{
515 if (hLibintlDLL)
516 FreeLibrary(hLibintlDLL);
517 hLibintlDLL = NULL;
518 dyn_libintl_gettext = null_libintl_gettext;
519 dyn_libintl_textdomain = null_libintl_textdomain;
520 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000521 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522}
523
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000524/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000525 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000526null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000527{
528 return (char*)msgid;
529}
530
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000531/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000532 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000533null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000534{
535 return NULL;
536}
537
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000538/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000539 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000540null_libintl_bind_textdomain_codeset(const char *domainname,
541 const char *codeset)
542{
543 return NULL;
544}
545
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000546/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000547 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000548null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549{
550 return NULL;
551}
552
553#endif /* DYNAMIC_GETTEXT */
554
555/* This symbol is not defined in older versions of the SDK or Visual C++ */
556
557#ifndef VER_PLATFORM_WIN32_WINDOWS
558# define VER_PLATFORM_WIN32_WINDOWS 1
559#endif
560
561DWORD g_PlatformId;
562
563#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100564# ifndef PROTO
565# include <aclapi.h>
566# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200567# ifndef PROTECTED_DACL_SECURITY_INFORMATION
568# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
569# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100570
Bram Moolenaar071d4272004-06-13 20:20:40 +0000571/*
572 * These are needed to dynamically load the ADVAPI DLL, which is not
573 * implemented under Windows 95 (and causes VIM to crash)
574 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200575typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000576 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200577typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000578 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
579 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200580# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200581typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200582 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200583typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200584 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
585 PSECURITY_DESCRIPTOR *);
586# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000587
588static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
589static PSNSECINFO pSetNamedSecurityInfo;
590static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200591# ifdef FEAT_MBYTE
592static PSNSECINFOW pSetNamedSecurityInfoW;
593static PGNSECINFOW pGetNamedSecurityInfoW;
594# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000595#endif
596
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200597typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
598
599static BOOL allowPiping = FALSE;
600static PSETHANDLEINFORMATION pSetHandleInformation;
601
Bram Moolenaar27515922013-06-29 15:36:26 +0200602#ifdef HAVE_ACL
603/*
604 * Enables or disables the specified privilege.
605 */
606 static BOOL
607win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
608{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100609 BOOL bResult;
610 LUID luid;
611 HANDLE hToken;
612 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200613
614 if (!OpenProcessToken(GetCurrentProcess(),
615 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
616 return FALSE;
617
618 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
619 {
620 CloseHandle(hToken);
621 return FALSE;
622 }
623
Bram Moolenaar45500912014-07-09 20:51:07 +0200624 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200625 tokenPrivileges.Privileges[0].Luid = luid;
626 tokenPrivileges.Privileges[0].Attributes = bEnable ?
627 SE_PRIVILEGE_ENABLED : 0;
628
629 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
630 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
631
632 CloseHandle(hToken);
633
634 return bResult && GetLastError() == ERROR_SUCCESS;
635}
636#endif
637
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638/*
639 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
640 * VER_PLATFORM_WIN32_WINDOWS (Win95).
641 */
642 void
643PlatformId(void)
644{
645 static int done = FALSE;
646
647 if (!done)
648 {
649 OSVERSIONINFO ovi;
650
651 ovi.dwOSVersionInfoSize = sizeof(ovi);
652 GetVersionEx(&ovi);
653
654 g_PlatformId = ovi.dwPlatformId;
655
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100656 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
657 || ovi.dwMajorVersion > 6)
658 win8_or_later = TRUE;
659
Bram Moolenaar071d4272004-06-13 20:20:40 +0000660#ifdef HAVE_ACL
661 /*
662 * Load the ADVAPI runtime if we are on anything
663 * other than Windows 95
664 */
665 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
666 {
667 /*
668 * do this load. Problems: Doesn't unload at end of run (this is
669 * theoretically okay, since Windows should unload it when VIM
670 * terminates). Should we be using the 'mch_libcall' routines?
671 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
672 * time we verify security...
673 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200674 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000675 if (advapi_lib != NULL)
676 {
677 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
678 "SetNamedSecurityInfoA");
679 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
680 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200681# ifdef FEAT_MBYTE
682 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
683 "SetNamedSecurityInfoW");
684 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
685 "GetNamedSecurityInfoW");
686# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000687 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200688 || pGetNamedSecurityInfo == NULL
689# ifdef FEAT_MBYTE
690 || pSetNamedSecurityInfoW == NULL
691 || pGetNamedSecurityInfoW == NULL
692# endif
693 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000694 {
695 /* If we can't get the function addresses, set advapi_lib
696 * to NULL so that we don't use them. */
697 FreeLibrary(advapi_lib);
698 advapi_lib = NULL;
699 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200700 /* Enable privilege for getting or setting SACLs. */
701 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702 }
703 }
704#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200705 /*
706 * If we are on windows NT, try to load the pipe functions, only
707 * available from Win2K.
708 */
709 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
710 {
711 HANDLE kernel32 = GetModuleHandle("kernel32");
712 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
713 kernel32, "SetHandleInformation");
714
715 allowPiping = pSetHandleInformation != NULL;
716 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717 done = TRUE;
718 }
719}
720
721/*
722 * Return TRUE when running on Windows 95 (or 98 or ME).
723 * Only to be used after mch_init().
724 */
725 int
726mch_windows95(void)
727{
728 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
729}
730
731#ifdef FEAT_GUI_W32
732/*
733 * Used to work around the "can't do synchronous spawn"
734 * problem on Win32s, without resorting to Universal Thunk.
735 */
736static int old_num_windows;
737static int num_windows;
738
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000739/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740 static BOOL CALLBACK
741win32ssynch_cb(HWND hwnd, LPARAM lparam)
742{
743 num_windows++;
744 return TRUE;
745}
746#endif
747
748#ifndef FEAT_GUI_W32
749
750#define SHIFT (SHIFT_PRESSED)
751#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
752#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
753#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
754
755
756/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
757 * We map function keys to their ANSI terminal equivalents, as produced
758 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
759 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
760 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
761 * combinations of function/arrow/etc keys.
762 */
763
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000764static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000765{
766 WORD wVirtKey;
767 BOOL fAnsiKey;
768 int chAlone;
769 int chShift;
770 int chCtrl;
771 int chAlt;
772} VirtKeyMap[] =
773{
774
775/* Key ANSI alone shift ctrl alt */
776 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
777
778 { VK_F1, TRUE, ';', 'T', '^', 'h', },
779 { VK_F2, TRUE, '<', 'U', '_', 'i', },
780 { VK_F3, TRUE, '=', 'V', '`', 'j', },
781 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
782 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
783 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
784 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
785 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
786 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
787 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
788 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
789 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
790
791 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
792 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
793 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
794 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
795 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
796 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
797 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
798 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
799 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
800 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
801
802 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
803
804#if 0
805 /* Most people don't have F13-F20, but what the hell... */
806 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
807 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
808 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
809 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
810 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
811 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
812 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
813 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
814#endif
815 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
816 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
817 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
818 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
819
820 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
821 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
822 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
823 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
824 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
825 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
826 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
827 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
828 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
829 /* Sorry, out of number space! <negri>*/
830 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
831
832};
833
834
835#ifdef _MSC_VER
836// The ToAscii bug destroys several registers. Need to turn off optimization
837// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000838# pragma warning(push)
839# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000840# pragma optimize("", off)
841#endif
842
843#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
844# define AChar AsciiChar
845#else
846# define AChar uChar.AsciiChar
847#endif
848
849/* The return code indicates key code size. */
850 static int
851#ifdef __BORLANDC__
852 __stdcall
853#endif
854win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000855 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000856{
857 UINT uMods = pker->dwControlKeyState;
858 static int s_iIsDead = 0;
859 static WORD awAnsiCode[2];
860 static BYTE abKeystate[256];
861
862
863 if (s_iIsDead == 2)
864 {
865 pker->AChar = (CHAR) awAnsiCode[1];
866 s_iIsDead = 0;
867 return 1;
868 }
869
870 if (pker->AChar != 0)
871 return 1;
872
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200873 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874
875 // Should only be non-NULL on NT 4.0
876 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
877 {
878 CHAR szKLID[KL_NAMELENGTH];
879
880 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
881 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
882 }
883
884 /* Clear any pending dead keys */
885 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
886
887 if (uMods & SHIFT_PRESSED)
888 abKeystate[VK_SHIFT] = 0x80;
889 if (uMods & CAPSLOCK_ON)
890 abKeystate[VK_CAPITAL] = 1;
891
892 if ((uMods & ALT_GR) == ALT_GR)
893 {
894 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
895 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
896 }
897
898 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
899 abKeystate, awAnsiCode, 0);
900
901 if (s_iIsDead > 0)
902 pker->AChar = (CHAR) awAnsiCode[0];
903
904 return s_iIsDead;
905}
906
907#ifdef _MSC_VER
908/* MUST switch optimization on again here, otherwise a call to
909 * decode_key_event() may crash (e.g. when hitting caps-lock) */
910# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000911# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912
913# if (_MSC_VER < 1100)
914/* MUST turn off global optimisation for this next function, or
915 * pressing ctrl-minus in insert mode crashes Vim when built with
916 * VC4.1. -- negri. */
917# pragma optimize("g", off)
918# endif
919#endif
920
921static BOOL g_fJustGotFocus = FALSE;
922
923/*
924 * Decode a KEY_EVENT into one or two keystrokes
925 */
926 static BOOL
927decode_key_event(
928 KEY_EVENT_RECORD *pker,
929 char_u *pch,
930 char_u *pch2,
931 int *pmodifiers,
932 BOOL fDoPost)
933{
934 int i;
935 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
936
937 *pch = *pch2 = NUL;
938 g_fJustGotFocus = FALSE;
939
940 /* ignore key up events */
941 if (!pker->bKeyDown)
942 return FALSE;
943
944 /* ignore some keystrokes */
945 switch (pker->wVirtualKeyCode)
946 {
947 /* modifiers */
948 case VK_SHIFT:
949 case VK_CONTROL:
950 case VK_MENU: /* Alt key */
951 return FALSE;
952
953 default:
954 break;
955 }
956
957 /* special cases */
958 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
959 {
960 /* Ctrl-6 is Ctrl-^ */
961 if (pker->wVirtualKeyCode == '6')
962 {
963 *pch = Ctrl_HAT;
964 return TRUE;
965 }
966 /* Ctrl-2 is Ctrl-@ */
967 else if (pker->wVirtualKeyCode == '2')
968 {
969 *pch = NUL;
970 return TRUE;
971 }
972 /* Ctrl-- is Ctrl-_ */
973 else if (pker->wVirtualKeyCode == 0xBD)
974 {
975 *pch = Ctrl__;
976 return TRUE;
977 }
978 }
979
980 /* Shift-TAB */
981 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
982 {
983 *pch = K_NUL;
984 *pch2 = '\017';
985 return TRUE;
986 }
987
988 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
989 {
990 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
991 {
992 if (nModifs == 0)
993 *pch = VirtKeyMap[i].chAlone;
994 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
995 *pch = VirtKeyMap[i].chShift;
996 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
997 *pch = VirtKeyMap[i].chCtrl;
998 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
999 *pch = VirtKeyMap[i].chAlt;
1000
1001 if (*pch != 0)
1002 {
1003 if (VirtKeyMap[i].fAnsiKey)
1004 {
1005 *pch2 = *pch;
1006 *pch = K_NUL;
1007 }
1008
1009 return TRUE;
1010 }
1011 }
1012 }
1013
1014 i = win32_kbd_patch_key(pker);
1015
1016 if (i < 0)
1017 *pch = NUL;
1018 else
1019 {
1020 *pch = (i > 0) ? pker->AChar : NUL;
1021
1022 if (pmodifiers != NULL)
1023 {
1024 /* Pass on the ALT key as a modifier, but only when not combined
1025 * with CTRL (which is ALTGR). */
1026 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1027 *pmodifiers |= MOD_MASK_ALT;
1028
1029 /* Pass on SHIFT only for special keys, because we don't know when
1030 * it's already included with the character. */
1031 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1032 *pmodifiers |= MOD_MASK_SHIFT;
1033
1034 /* Pass on CTRL only for non-special keys, because we don't know
1035 * when it's already included with the character. And not when
1036 * combined with ALT (which is ALTGR). */
1037 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1038 && *pch >= 0x20 && *pch < 0x80)
1039 *pmodifiers |= MOD_MASK_CTRL;
1040 }
1041 }
1042
1043 return (*pch != NUL);
1044}
1045
1046#ifdef _MSC_VER
1047# pragma optimize("", on)
1048#endif
1049
1050#endif /* FEAT_GUI_W32 */
1051
1052
1053#ifdef FEAT_MOUSE
1054
1055/*
1056 * For the GUI the mouse handling is in gui_w32.c.
1057 */
1058# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001059/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001060 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001061mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001062{
1063}
1064# else
1065static int g_fMouseAvail = FALSE; /* mouse present */
1066static int g_fMouseActive = FALSE; /* mouse enabled */
1067static int g_nMouseClick = -1; /* mouse status */
1068static int g_xMouse; /* mouse x coordinate */
1069static int g_yMouse; /* mouse y coordinate */
1070
1071/*
1072 * Enable or disable mouse input
1073 */
1074 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001075mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001076{
1077 DWORD cmodein;
1078
1079 if (!g_fMouseAvail)
1080 return;
1081
1082 g_fMouseActive = on;
1083 GetConsoleMode(g_hConIn, &cmodein);
1084
1085 if (g_fMouseActive)
1086 cmodein |= ENABLE_MOUSE_INPUT;
1087 else
1088 cmodein &= ~ENABLE_MOUSE_INPUT;
1089
1090 SetConsoleMode(g_hConIn, cmodein);
1091}
1092
1093
1094/*
1095 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1096 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1097 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1098 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1099 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1100 * and we return the mouse position in g_xMouse and g_yMouse.
1101 *
1102 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1103 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1104 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1105 *
1106 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1107 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1108 *
1109 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1110 * moves, even if it stays within the same character cell. We ignore
1111 * all MOUSE_MOVED messages if the position hasn't really changed, and
1112 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1113 * we're only interested in MOUSE_DRAG).
1114 *
1115 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1116 * 2-button mouses by pressing the left & right buttons simultaneously.
1117 * In practice, it's almost impossible to click both at the same time,
1118 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1119 * in such cases, if the user is clicking quickly.
1120 */
1121 static BOOL
1122decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001123 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001124{
1125 static int s_nOldButton = -1;
1126 static int s_nOldMouseClick = -1;
1127 static int s_xOldMouse = -1;
1128 static int s_yOldMouse = -1;
1129 static linenr_T s_old_topline = 0;
1130#ifdef FEAT_DIFF
1131 static int s_old_topfill = 0;
1132#endif
1133 static int s_cClicks = 1;
1134 static BOOL s_fReleased = TRUE;
1135 static DWORD s_dwLastClickTime = 0;
1136 static BOOL s_fNextIsMiddle = FALSE;
1137
1138 static DWORD cButtons = 0; /* number of buttons supported */
1139
1140 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1141 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1142 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1143 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1144
1145 int nButton;
1146
1147 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1148 cButtons = 2;
1149
1150 if (!g_fMouseAvail || !g_fMouseActive)
1151 {
1152 g_nMouseClick = -1;
1153 return FALSE;
1154 }
1155
1156 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1157 if (g_fJustGotFocus)
1158 {
1159 g_fJustGotFocus = FALSE;
1160 return FALSE;
1161 }
1162
1163 /* unprocessed mouse click? */
1164 if (g_nMouseClick != -1)
1165 return TRUE;
1166
1167 nButton = -1;
1168 g_xMouse = pmer->dwMousePosition.X;
1169 g_yMouse = pmer->dwMousePosition.Y;
1170
1171 if (pmer->dwEventFlags == MOUSE_MOVED)
1172 {
1173 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1174 * events even when the mouse moves only within a char cell.) */
1175 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1176 return FALSE;
1177 }
1178
1179 /* If no buttons are pressed... */
1180 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1181 {
1182 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1183 if (s_fReleased)
1184 return FALSE;
1185
1186 nButton = MOUSE_RELEASE;
1187 s_fReleased = TRUE;
1188 }
1189 else /* one or more buttons pressed */
1190 {
1191 /* on a 2-button mouse, hold down left and right buttons
1192 * simultaneously to get MIDDLE. */
1193
1194 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1195 {
1196 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1197
1198 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001199 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001200 if (dwLR == LEFT || dwLR == RIGHT)
1201 {
1202 for (;;)
1203 {
1204 /* wait a short time for next input event */
1205 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1206 != WAIT_OBJECT_0)
1207 break;
1208 else
1209 {
1210 DWORD cRecords = 0;
1211 INPUT_RECORD ir;
1212 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1213
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001214 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001215
1216 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1217 || !(pmer2->dwButtonState & LEFT_RIGHT))
1218 break;
1219 else
1220 {
1221 if (pmer2->dwEventFlags != MOUSE_MOVED)
1222 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001223 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001224
1225 return decode_mouse_event(pmer2);
1226 }
1227 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1228 s_yOldMouse == pmer2->dwMousePosition.Y)
1229 {
1230 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001231 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001232
1233 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001234 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001235
1236 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1237 break;
1238 }
1239 else
1240 break;
1241 }
1242 }
1243 }
1244 }
1245 }
1246
1247 if (s_fNextIsMiddle)
1248 {
1249 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1250 ? MOUSE_DRAG : MOUSE_MIDDLE;
1251 s_fNextIsMiddle = FALSE;
1252 }
1253 else if (cButtons == 2 &&
1254 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1255 {
1256 nButton = MOUSE_MIDDLE;
1257
1258 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1259 {
1260 s_fNextIsMiddle = TRUE;
1261 nButton = MOUSE_RELEASE;
1262 }
1263 }
1264 else if ((pmer->dwButtonState & LEFT) == LEFT)
1265 nButton = MOUSE_LEFT;
1266 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1267 nButton = MOUSE_MIDDLE;
1268 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1269 nButton = MOUSE_RIGHT;
1270
1271 if (! s_fReleased && ! s_fNextIsMiddle
1272 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1273 return FALSE;
1274
1275 s_fReleased = s_fNextIsMiddle;
1276 }
1277
1278 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1279 {
1280 /* button pressed or released, without mouse moving */
1281 if (nButton != -1 && nButton != MOUSE_RELEASE)
1282 {
1283 DWORD dwCurrentTime = GetTickCount();
1284
1285 if (s_xOldMouse != g_xMouse
1286 || s_yOldMouse != g_yMouse
1287 || s_nOldButton != nButton
1288 || s_old_topline != curwin->w_topline
1289#ifdef FEAT_DIFF
1290 || s_old_topfill != curwin->w_topfill
1291#endif
1292 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1293 {
1294 s_cClicks = 1;
1295 }
1296 else if (++s_cClicks > 4)
1297 {
1298 s_cClicks = 1;
1299 }
1300
1301 s_dwLastClickTime = dwCurrentTime;
1302 }
1303 }
1304 else if (pmer->dwEventFlags == MOUSE_MOVED)
1305 {
1306 if (nButton != -1 && nButton != MOUSE_RELEASE)
1307 nButton = MOUSE_DRAG;
1308
1309 s_cClicks = 1;
1310 }
1311
1312 if (nButton == -1)
1313 return FALSE;
1314
1315 if (nButton != MOUSE_RELEASE)
1316 s_nOldButton = nButton;
1317
1318 g_nMouseClick = nButton;
1319
1320 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1321 g_nMouseClick |= MOUSE_SHIFT;
1322 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1323 g_nMouseClick |= MOUSE_CTRL;
1324 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1325 g_nMouseClick |= MOUSE_ALT;
1326
1327 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1328 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1329
1330 /* only pass on interesting (i.e., different) mouse events */
1331 if (s_xOldMouse == g_xMouse
1332 && s_yOldMouse == g_yMouse
1333 && s_nOldMouseClick == g_nMouseClick)
1334 {
1335 g_nMouseClick = -1;
1336 return FALSE;
1337 }
1338
1339 s_xOldMouse = g_xMouse;
1340 s_yOldMouse = g_yMouse;
1341 s_old_topline = curwin->w_topline;
1342#ifdef FEAT_DIFF
1343 s_old_topfill = curwin->w_topfill;
1344#endif
1345 s_nOldMouseClick = g_nMouseClick;
1346
1347 return TRUE;
1348}
1349
1350# endif /* FEAT_GUI_W32 */
1351#endif /* FEAT_MOUSE */
1352
1353
1354#ifdef MCH_CURSOR_SHAPE
1355/*
1356 * Set the shape of the cursor.
1357 * 'thickness' can be from 1 (thin) to 99 (block)
1358 */
1359 static void
1360mch_set_cursor_shape(int thickness)
1361{
1362 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1363 ConsoleCursorInfo.dwSize = thickness;
1364 ConsoleCursorInfo.bVisible = s_cursor_visible;
1365
1366 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1367 if (s_cursor_visible)
1368 SetConsoleCursorPosition(g_hConOut, g_coord);
1369}
1370
1371 void
1372mch_update_cursor(void)
1373{
1374 int idx;
1375 int thickness;
1376
1377 /*
1378 * How the cursor is drawn depends on the current mode.
1379 */
1380 idx = get_shape_idx(FALSE);
1381
1382 if (shape_table[idx].shape == SHAPE_BLOCK)
1383 thickness = 99; /* 100 doesn't work on W95 */
1384 else
1385 thickness = shape_table[idx].percentage;
1386 mch_set_cursor_shape(thickness);
1387}
1388#endif
1389
1390#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1391/*
1392 * Handle FOCUS_EVENT.
1393 */
1394 static void
1395handle_focus_event(INPUT_RECORD ir)
1396{
1397 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1398 ui_focus_change((int)g_fJustGotFocus);
1399}
1400
1401/*
1402 * Wait until console input from keyboard or mouse is available,
1403 * or the time is up.
1404 * Return TRUE if something is available FALSE if not.
1405 */
1406 static int
1407WaitForChar(long msec)
1408{
1409 DWORD dwNow = 0, dwEndTime = 0;
1410 INPUT_RECORD ir;
1411 DWORD cRecords;
1412 char_u ch, ch2;
1413
1414 if (msec > 0)
1415 /* Wait until the specified time has elapsed. */
1416 dwEndTime = GetTickCount() + msec;
1417 else if (msec < 0)
1418 /* Wait forever. */
1419 dwEndTime = INFINITE;
1420
1421 /* We need to loop until the end of the time period, because
1422 * we might get multiple unusable mouse events in that time.
1423 */
1424 for (;;)
1425 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001426#ifdef FEAT_MZSCHEME
1427 mzvim_check_threads();
1428#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001429#ifdef FEAT_CLIENTSERVER
1430 serverProcessPendingMessages();
1431#endif
1432 if (0
1433#ifdef FEAT_MOUSE
1434 || g_nMouseClick != -1
1435#endif
1436#ifdef FEAT_CLIENTSERVER
1437 || input_available()
1438#endif
1439 )
1440 return TRUE;
1441
1442 if (msec > 0)
1443 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001444 /* If the specified wait time has passed, return. Beware that
1445 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001446 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001447 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448 break;
1449 }
1450 if (msec != 0)
1451 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001452 DWORD dwWaitTime = dwEndTime - dwNow;
1453
1454#ifdef FEAT_MZSCHEME
1455 if (mzthreads_allowed() && p_mzq > 0
1456 && (msec < 0 || (long)dwWaitTime > p_mzq))
1457 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1458#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001459#ifdef FEAT_CLIENTSERVER
1460 /* Wait for either an event on the console input or a message in
1461 * the client-server window. */
1462 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001463 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001464#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001465 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466#endif
1467 continue;
1468 }
1469
1470 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001471 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472
1473#ifdef FEAT_MBYTE_IME
1474 if (State & CMDLINE && msg_row == Rows - 1)
1475 {
1476 CONSOLE_SCREEN_BUFFER_INFO csbi;
1477
1478 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1479 {
1480 if (csbi.dwCursorPosition.Y != msg_row)
1481 {
1482 /* The screen is now messed up, must redraw the
1483 * command line and later all the windows. */
1484 redraw_all_later(CLEAR);
1485 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1486 redrawcmd();
1487 }
1488 }
1489 }
1490#endif
1491
1492 if (cRecords > 0)
1493 {
1494 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1495 {
1496#ifdef FEAT_MBYTE_IME
1497 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1498 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1499 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1500 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1501 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001502 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503 continue;
1504 }
1505#endif
1506 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1507 NULL, FALSE))
1508 return TRUE;
1509 }
1510
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001511 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001512
1513 if (ir.EventType == FOCUS_EVENT)
1514 handle_focus_event(ir);
1515 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1516 shell_resized();
1517#ifdef FEAT_MOUSE
1518 else if (ir.EventType == MOUSE_EVENT
1519 && decode_mouse_event(&ir.Event.MouseEvent))
1520 return TRUE;
1521#endif
1522 }
1523 else if (msec == 0)
1524 break;
1525 }
1526
1527#ifdef FEAT_CLIENTSERVER
1528 /* Something might have been received while we were waiting. */
1529 if (input_available())
1530 return TRUE;
1531#endif
1532 return FALSE;
1533}
1534
1535#ifndef FEAT_GUI_MSWIN
1536/*
1537 * return non-zero if a character is available
1538 */
1539 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001540mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001541{
1542 return WaitForChar(0L);
1543}
1544#endif
1545
1546/*
1547 * Create the console input. Used when reading stdin doesn't work.
1548 */
1549 static void
1550create_conin(void)
1551{
1552 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1553 FILE_SHARE_READ|FILE_SHARE_WRITE,
1554 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001555 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001556 did_create_conin = TRUE;
1557}
1558
1559/*
1560 * Get a keystroke or a mouse event
1561 */
1562 static char_u
1563tgetch(int *pmodifiers, char_u *pch2)
1564{
1565 char_u ch;
1566
1567 for (;;)
1568 {
1569 INPUT_RECORD ir;
1570 DWORD cRecords = 0;
1571
1572#ifdef FEAT_CLIENTSERVER
1573 (void)WaitForChar(-1L);
1574 if (input_available())
1575 return 0;
1576# ifdef FEAT_MOUSE
1577 if (g_nMouseClick != -1)
1578 return 0;
1579# endif
1580#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001581 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582 {
1583 if (did_create_conin)
1584 read_error_exit();
1585 create_conin();
1586 continue;
1587 }
1588
1589 if (ir.EventType == KEY_EVENT)
1590 {
1591 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1592 pmodifiers, TRUE))
1593 return ch;
1594 }
1595 else if (ir.EventType == FOCUS_EVENT)
1596 handle_focus_event(ir);
1597 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1598 shell_resized();
1599#ifdef FEAT_MOUSE
1600 else if (ir.EventType == MOUSE_EVENT)
1601 {
1602 if (decode_mouse_event(&ir.Event.MouseEvent))
1603 return 0;
1604 }
1605#endif
1606 }
1607}
1608#endif /* !FEAT_GUI_W32 */
1609
1610
1611/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001612 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613 * Get one or more characters from the keyboard or the mouse.
1614 * If time == 0, do not wait for characters.
1615 * If time == n, wait a short time for characters.
1616 * If time == -1, wait forever for characters.
1617 * Returns the number of characters read into buf.
1618 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001619/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 int
1621mch_inchar(
1622 char_u *buf,
1623 int maxlen,
1624 long time,
1625 int tb_change_cnt)
1626{
1627#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1628
1629 int len;
1630 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001631#define TYPEAHEADLEN 20
1632 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1633 static int typeaheadlen = 0;
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001634#ifdef FEAT_MBYTE
1635 static char_u *rest = NULL; /* unconverted rest of previous read */
1636 static int restlen = 0;
1637 int unconverted;
1638#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001639
1640 /* First use any typeahead that was kept because "buf" was too small. */
1641 if (typeaheadlen > 0)
1642 goto theend;
1643
1644#ifdef FEAT_SNIFF
1645 if (want_sniff_request)
1646 {
1647 if (sniff_request_waiting)
1648 {
1649 /* return K_SNIFF */
1650 typeahead[typeaheadlen++] = CSI;
1651 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1652 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1653 sniff_request_waiting = 0;
1654 want_sniff_request = 0;
1655 goto theend;
1656 }
1657 else if (time < 0 || time > 250)
1658 {
1659 /* don't wait too long, a request might be pending */
1660 time = 250;
1661 }
1662 }
1663#endif
1664
1665 if (time >= 0)
1666 {
1667 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669 }
1670 else /* time == -1, wait forever */
1671 {
1672 mch_set_winsize_now(); /* Allow winsize changes from now on */
1673
Bram Moolenaar3918c952005-03-15 22:34:55 +00001674 /*
1675 * If there is no character available within 2 seconds (default)
1676 * write the autoscript file to disk. Or cause the CursorHold event
1677 * to be triggered.
1678 */
1679 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001680 {
1681#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001682 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001684 buf[0] = K_SPECIAL;
1685 buf[1] = KS_EXTRA;
1686 buf[2] = (int)KE_CURSORHOLD;
1687 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688 }
1689#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001690 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691 }
1692 }
1693
1694 /*
1695 * Try to read as many characters as there are, until the buffer is full.
1696 */
1697
1698 /* we will get at least one key. Get more if they are available. */
1699 g_fCBrkPressed = FALSE;
1700
1701#ifdef MCH_WRITE_DUMP
1702 if (fdDump)
1703 fputc('[', fdDump);
1704#endif
1705
1706 /* Keep looping until there is something in the typeahead buffer and more
1707 * to get and still room in the buffer (up to two bytes for a char and
1708 * three bytes for a modifier). */
1709 while ((typeaheadlen == 0 || WaitForChar(0L))
1710 && typeaheadlen + 5 <= TYPEAHEADLEN)
1711 {
1712 if (typebuf_changed(tb_change_cnt))
1713 {
1714 /* "buf" may be invalid now if a client put something in the
1715 * typeahead buffer and "buf" is in the typeahead buffer. */
1716 typeaheadlen = 0;
1717 break;
1718 }
1719#ifdef FEAT_MOUSE
1720 if (g_nMouseClick != -1)
1721 {
1722# ifdef MCH_WRITE_DUMP
1723 if (fdDump)
1724 fprintf(fdDump, "{%02x @ %d, %d}",
1725 g_nMouseClick, g_xMouse, g_yMouse);
1726# endif
1727 typeahead[typeaheadlen++] = ESC + 128;
1728 typeahead[typeaheadlen++] = 'M';
1729 typeahead[typeaheadlen++] = g_nMouseClick;
1730 typeahead[typeaheadlen++] = g_xMouse + '!';
1731 typeahead[typeaheadlen++] = g_yMouse + '!';
1732 g_nMouseClick = -1;
1733 }
1734 else
1735#endif
1736 {
1737 char_u ch2 = NUL;
1738 int modifiers = 0;
1739
1740 c = tgetch(&modifiers, &ch2);
1741
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001742#ifdef FEAT_MBYTE
1743 /* stolen from fill_input_buf() in ui.c */
1744 if (rest != NULL)
1745 {
1746 /* Use remainder of previous call, starts with an invalid
1747 * character that may become valid when reading more. */
1748 if (restlen > TYPEAHEADLEN - typeaheadlen)
1749 unconverted = TYPEAHEADLEN - typeaheadlen;
1750 else
1751 unconverted = restlen;
1752 mch_memmove(typeahead + typeaheadlen, rest, unconverted);
1753 if (unconverted == restlen)
1754 {
1755 vim_free(rest);
1756 rest = NULL;
1757 }
1758 else
1759 {
1760 restlen -= unconverted;
1761 mch_memmove(rest, rest + unconverted, restlen);
1762 }
1763 typeaheadlen += unconverted;
1764 }
1765 else
1766 unconverted = 0;
1767#endif
1768
Bram Moolenaar071d4272004-06-13 20:20:40 +00001769 if (typebuf_changed(tb_change_cnt))
1770 {
1771 /* "buf" may be invalid now if a client put something in the
1772 * typeahead buffer and "buf" is in the typeahead buffer. */
1773 typeaheadlen = 0;
1774 break;
1775 }
1776
1777 if (c == Ctrl_C && ctrl_c_interrupts)
1778 {
1779#if defined(FEAT_CLIENTSERVER)
1780 trash_input_buf();
1781#endif
1782 got_int = TRUE;
1783 }
1784
1785#ifdef FEAT_MOUSE
1786 if (g_nMouseClick == -1)
1787#endif
1788 {
1789 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001790 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792 typeahead[typeaheadlen] = c;
1793 if (ch2 != NUL)
1794 {
Bram Moolenaar45500912014-07-09 20:51:07 +02001795 typeahead[typeaheadlen + 1] = 3;
1796 typeahead[typeaheadlen + 2] = ch2;
1797 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798 }
1799#ifdef FEAT_MBYTE
1800 /* Only convert normal characters, not special keys. Need to
1801 * convert before applying ALT, otherwise mapping <M-x> breaks
1802 * when 'tenc' is set. */
1803 if (input_conv.vc_type != CONV_NONE
1804 && (ch2 == NUL || c != K_NUL))
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001805 {
Bram Moolenaar45500912014-07-09 20:51:07 +02001806 conv = TRUE;
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001807 typeaheadlen -= unconverted;
1808 n = convert_input_safe(typeahead + typeaheadlen,
1809 n + unconverted, TYPEAHEADLEN - typeaheadlen,
1810 rest == NULL ? &rest : NULL, &restlen);
1811 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001812#endif
1813
Bram Moolenaar45500912014-07-09 20:51:07 +02001814 if (conv)
1815 {
1816 char_u *p = typeahead + typeaheadlen;
1817 char_u *e = typeahead + TYPEAHEADLEN;
1818
1819 while (*p && p < e)
1820 {
1821 if (*p == K_NUL)
1822 {
1823 ++p;
1824 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1825 *p = 3;
1826 ++n;
1827 }
1828 ++p;
1829 }
1830 }
1831
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 /* Use the ALT key to set the 8th bit of the character
1833 * when it's one byte, the 8th bit isn't set yet and not
1834 * using a double-byte encoding (would become a lead
1835 * byte). */
1836 if ((modifiers & MOD_MASK_ALT)
1837 && n == 1
1838 && (typeahead[typeaheadlen] & 0x80) == 0
1839#ifdef FEAT_MBYTE
1840 && !enc_dbcs
1841#endif
1842 )
1843 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001844#ifdef FEAT_MBYTE
1845 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1846 typeahead + typeaheadlen);
1847#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001848 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001849#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 modifiers &= ~MOD_MASK_ALT;
1851 }
1852
1853 if (modifiers != 0)
1854 {
1855 /* Prepend modifiers to the character. */
1856 mch_memmove(typeahead + typeaheadlen + 3,
1857 typeahead + typeaheadlen, n);
1858 typeahead[typeaheadlen++] = K_SPECIAL;
1859 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1860 typeahead[typeaheadlen++] = modifiers;
1861 }
1862
1863 typeaheadlen += n;
1864
1865#ifdef MCH_WRITE_DUMP
1866 if (fdDump)
1867 fputc(c, fdDump);
1868#endif
1869 }
1870 }
1871 }
1872
1873#ifdef MCH_WRITE_DUMP
1874 if (fdDump)
1875 {
1876 fputs("]\n", fdDump);
1877 fflush(fdDump);
1878 }
1879#endif
1880
Bram Moolenaar071d4272004-06-13 20:20:40 +00001881theend:
1882 /* Move typeahead to "buf", as much as fits. */
1883 len = 0;
1884 while (len < maxlen && typeaheadlen > 0)
1885 {
1886 buf[len++] = typeahead[0];
1887 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1888 }
1889 return len;
1890
1891#else /* FEAT_GUI_W32 */
1892 return 0;
1893#endif /* FEAT_GUI_W32 */
1894}
1895
Bram Moolenaar82881492012-11-20 16:53:39 +01001896#ifndef PROTO
1897# ifndef __MINGW32__
1898# include <shellapi.h> /* required for FindExecutable() */
1899# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900#endif
1901
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001902/*
1903 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001904 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001905 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001906 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001907executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001909 char *dum;
1910 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001911 char *curpath, *newpath;
1912 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001913
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001914#ifdef FEAT_MBYTE
1915 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001917 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001918 WCHAR fnamew[_MAX_PATH];
1919 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001920 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001921
1922 if (p != NULL)
1923 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001924 wcurpath = _wgetenv(L"PATH");
1925 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1926 * sizeof(WCHAR));
1927 if (wnewpath == NULL)
1928 return FALSE;
1929 wcscpy(wnewpath, L".;");
1930 wcscat(wnewpath, wcurpath);
1931 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1932 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001933 vim_free(p);
1934 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1935 {
1936 if (n == 0)
1937 return FALSE;
1938 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1939 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001940 if (path != NULL)
1941 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001942 return TRUE;
1943 }
1944 /* Retry with non-wide function (for Windows 98). */
1945 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001946 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001947#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001948
1949 curpath = getenv("PATH");
1950 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1951 if (newpath == NULL)
1952 return FALSE;
1953 STRCPY(newpath, ".;");
1954 STRCAT(newpath, curpath);
1955 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1956 vim_free(newpath);
1957 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001958 return FALSE;
1959 if (mch_isdir(fname))
1960 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001961 if (path != NULL)
1962 *path = vim_strsave(fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001963 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964}
1965
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001966#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001967 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001968/*
1969 * Bad parameter handler.
1970 *
1971 * Certain MS CRT functions will intentionally crash when passed invalid
1972 * parameters to highlight possible security holes. Setting this function as
1973 * the bad parameter handler will prevent the crash.
1974 *
1975 * In debug builds the parameters contain CRT information that might help track
1976 * down the source of a problem, but in non-debug builds the arguments are all
1977 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1978 * worth allowing these to make debugging of issues easier.
1979 */
1980 static void
1981bad_param_handler(const wchar_t *expression,
1982 const wchar_t *function,
1983 const wchar_t *file,
1984 unsigned int line,
1985 uintptr_t pReserved)
1986{
1987}
1988
1989# define SET_INVALID_PARAM_HANDLER \
1990 ((void)_set_invalid_parameter_handler(bad_param_handler))
1991#else
1992# define SET_INVALID_PARAM_HANDLER
1993#endif
1994
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995#ifdef FEAT_GUI_W32
1996
1997/*
1998 * GUI version of mch_init().
1999 */
2000 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002001mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002{
2003#ifndef __MINGW32__
2004 extern int _fmode;
2005#endif
2006
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002007 /* Silently handle invalid parameters to CRT functions */
2008 SET_INVALID_PARAM_HANDLER;
2009
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010 /* Let critical errors result in a failure, not in a dialog box. Required
2011 * for the timestamp test to work on removed floppies. */
2012 SetErrorMode(SEM_FAILCRITICALERRORS);
2013
2014 _fmode = O_BINARY; /* we do our own CR-LF translation */
2015
2016 /* Specify window size. Is there a place to get the default from? */
2017 Rows = 25;
2018 Columns = 80;
2019
2020 /* Look for 'vimrun' */
2021 if (!gui_is_win32s())
2022 {
2023 char_u vimrun_location[_MAX_PATH + 4];
2024
2025 /* First try in same directory as gvim.exe */
2026 STRCPY(vimrun_location, exe_name);
2027 STRCPY(gettail(vimrun_location), "vimrun.exe");
2028 if (mch_getperm(vimrun_location) >= 0)
2029 {
2030 if (*skiptowhite(vimrun_location) != NUL)
2031 {
2032 /* Enclose path with white space in double quotes. */
2033 mch_memmove(vimrun_location + 1, vimrun_location,
2034 STRLEN(vimrun_location) + 1);
2035 *vimrun_location = '"';
2036 STRCPY(gettail(vimrun_location), "vimrun\" ");
2037 }
2038 else
2039 STRCPY(gettail(vimrun_location), "vimrun ");
2040
2041 vimrun_path = (char *)vim_strsave(vimrun_location);
2042 s_dont_use_vimrun = FALSE;
2043 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002044 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002045 s_dont_use_vimrun = FALSE;
2046
2047 /* Don't give the warning for a missing vimrun.exe right now, but only
2048 * when vimrun was supposed to be used. Don't bother people that do
2049 * not need vimrun.exe. */
2050 if (s_dont_use_vimrun)
2051 need_vimrun_warning = TRUE;
2052 }
2053
2054 /*
2055 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2056 * Otherwise the default "findstr /n" is used.
2057 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002058 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2060
2061#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002062 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002063#endif
2064}
2065
2066
2067#else /* FEAT_GUI_W32 */
2068
2069#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2070#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2071
2072/*
2073 * ClearConsoleBuffer()
2074 * Description:
2075 * Clears the entire contents of the console screen buffer, using the
2076 * specified attribute.
2077 * Returns:
2078 * TRUE on success
2079 */
2080 static BOOL
2081ClearConsoleBuffer(WORD wAttribute)
2082{
2083 CONSOLE_SCREEN_BUFFER_INFO csbi;
2084 COORD coord;
2085 DWORD NumCells, dummy;
2086
2087 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2088 return FALSE;
2089
2090 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2091 coord.X = 0;
2092 coord.Y = 0;
2093 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2094 coord, &dummy))
2095 {
2096 return FALSE;
2097 }
2098 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2099 coord, &dummy))
2100 {
2101 return FALSE;
2102 }
2103
2104 return TRUE;
2105}
2106
2107/*
2108 * FitConsoleWindow()
2109 * Description:
2110 * Checks if the console window will fit within given buffer dimensions.
2111 * Also, if requested, will shrink the window to fit.
2112 * Returns:
2113 * TRUE on success
2114 */
2115 static BOOL
2116FitConsoleWindow(
2117 COORD dwBufferSize,
2118 BOOL WantAdjust)
2119{
2120 CONSOLE_SCREEN_BUFFER_INFO csbi;
2121 COORD dwWindowSize;
2122 BOOL NeedAdjust = FALSE;
2123
2124 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2125 {
2126 /*
2127 * A buffer resize will fail if the current console window does
2128 * not lie completely within that buffer. To avoid this, we might
2129 * have to move and possibly shrink the window.
2130 */
2131 if (csbi.srWindow.Right >= dwBufferSize.X)
2132 {
2133 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2134 if (dwWindowSize.X > dwBufferSize.X)
2135 dwWindowSize.X = dwBufferSize.X;
2136 csbi.srWindow.Right = dwBufferSize.X - 1;
2137 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2138 NeedAdjust = TRUE;
2139 }
2140 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2141 {
2142 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2143 if (dwWindowSize.Y > dwBufferSize.Y)
2144 dwWindowSize.Y = dwBufferSize.Y;
2145 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2146 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2147 NeedAdjust = TRUE;
2148 }
2149 if (NeedAdjust && WantAdjust)
2150 {
2151 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2152 return FALSE;
2153 }
2154 return TRUE;
2155 }
2156
2157 return FALSE;
2158}
2159
2160typedef struct ConsoleBufferStruct
2161{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002162 BOOL IsValid;
2163 CONSOLE_SCREEN_BUFFER_INFO Info;
2164 PCHAR_INFO Buffer;
2165 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002166} ConsoleBuffer;
2167
2168/*
2169 * SaveConsoleBuffer()
2170 * Description:
2171 * Saves important information about the console buffer, including the
2172 * actual buffer contents. The saved information is suitable for later
2173 * restoration by RestoreConsoleBuffer().
2174 * Returns:
2175 * TRUE if all information was saved; FALSE otherwise
2176 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2177 */
2178 static BOOL
2179SaveConsoleBuffer(
2180 ConsoleBuffer *cb)
2181{
2182 DWORD NumCells;
2183 COORD BufferCoord;
2184 SMALL_RECT ReadRegion;
2185 WORD Y, Y_incr;
2186
2187 if (cb == NULL)
2188 return FALSE;
2189
2190 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
2191 {
2192 cb->IsValid = FALSE;
2193 return FALSE;
2194 }
2195 cb->IsValid = TRUE;
2196
2197 /*
2198 * Allocate a buffer large enough to hold the entire console screen
2199 * buffer. If this ConsoleBuffer structure has already been initialized
2200 * with a buffer of the correct size, then just use that one.
2201 */
2202 if (!cb->IsValid || cb->Buffer == NULL ||
2203 cb->BufferSize.X != cb->Info.dwSize.X ||
2204 cb->BufferSize.Y != cb->Info.dwSize.Y)
2205 {
2206 cb->BufferSize.X = cb->Info.dwSize.X;
2207 cb->BufferSize.Y = cb->Info.dwSize.Y;
2208 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
Bram Moolenaar3c2d6532011-02-01 13:48:53 +01002209 vim_free(cb->Buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2211 if (cb->Buffer == NULL)
2212 return FALSE;
2213 }
2214
2215 /*
2216 * We will now copy the console screen buffer into our buffer.
2217 * ReadConsoleOutput() seems to be limited as far as how much you
2218 * can read at a time. Empirically, this number seems to be about
2219 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2220 * in chunks until it is all copied. The chunks will all have the
2221 * same horizontal characteristics, so initialize them now. The
2222 * height of each chunk will be (12000 / width).
2223 */
2224 BufferCoord.X = 0;
2225 ReadRegion.Left = 0;
2226 ReadRegion.Right = cb->Info.dwSize.X - 1;
2227 Y_incr = 12000 / cb->Info.dwSize.X;
2228 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
2229 {
2230 /*
2231 * Read into position (0, Y) in our buffer.
2232 */
2233 BufferCoord.Y = Y;
2234 /*
2235 * Read the region whose top left corner is (0, Y) and whose bottom
2236 * right corner is (width - 1, Y + Y_incr - 1). This should define
2237 * a region of size width by Y_incr. Don't worry if this region is
2238 * too large for the remaining buffer; it will be cropped.
2239 */
2240 ReadRegion.Top = Y;
2241 ReadRegion.Bottom = Y + Y_incr - 1;
2242 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2243 cb->Buffer, /* our buffer */
2244 cb->BufferSize, /* dimensions of our buffer */
2245 BufferCoord, /* offset in our buffer */
2246 &ReadRegion)) /* region to save */
2247 {
2248 vim_free(cb->Buffer);
2249 cb->Buffer = NULL;
2250 return FALSE;
2251 }
2252 }
2253
2254 return TRUE;
2255}
2256
2257/*
2258 * RestoreConsoleBuffer()
2259 * Description:
2260 * Restores important information about the console buffer, including the
2261 * actual buffer contents, if desired. The information to restore is in
2262 * the same format used by SaveConsoleBuffer().
2263 * Returns:
2264 * TRUE on success
2265 */
2266 static BOOL
2267RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002268 ConsoleBuffer *cb,
2269 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002270{
2271 COORD BufferCoord;
2272 SMALL_RECT WriteRegion;
2273
2274 if (cb == NULL || !cb->IsValid)
2275 return FALSE;
2276
2277 /*
2278 * Before restoring the buffer contents, clear the current buffer, and
2279 * restore the cursor position and window information. Doing this now
2280 * prevents old buffer contents from "flashing" onto the screen.
2281 */
2282 if (RestoreScreen)
2283 ClearConsoleBuffer(cb->Info.wAttributes);
2284
2285 FitConsoleWindow(cb->Info.dwSize, TRUE);
2286 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2287 return FALSE;
2288 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2289 return FALSE;
2290
2291 if (!RestoreScreen)
2292 {
2293 /*
2294 * No need to restore the screen buffer contents, so we're done.
2295 */
2296 return TRUE;
2297 }
2298
2299 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2300 return FALSE;
2301 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2302 return FALSE;
2303
2304 /*
2305 * Restore the screen buffer contents.
2306 */
2307 if (cb->Buffer != NULL)
2308 {
2309 BufferCoord.X = 0;
2310 BufferCoord.Y = 0;
2311 WriteRegion.Left = 0;
2312 WriteRegion.Top = 0;
2313 WriteRegion.Right = cb->Info.dwSize.X - 1;
2314 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2315 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2316 cb->Buffer, /* our buffer */
2317 cb->BufferSize, /* dimensions of our buffer */
2318 BufferCoord, /* offset in our buffer */
2319 &WriteRegion)) /* region to restore */
2320 {
2321 return FALSE;
2322 }
2323 }
2324
2325 return TRUE;
2326}
2327
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002328#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002329#ifdef FEAT_RESTORE_ORIG_SCREEN
2330static ConsoleBuffer g_cbOrig = { 0 };
2331#endif
2332static ConsoleBuffer g_cbNonTermcap = { 0 };
2333static ConsoleBuffer g_cbTermcap = { 0 };
2334
2335#ifdef FEAT_TITLE
2336#ifdef __BORLANDC__
2337typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2338#else
2339typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2340#endif
2341char g_szOrigTitle[256] = { 0 };
2342HWND g_hWnd = NULL; /* also used in os_mswin.c */
2343static HICON g_hOrigIconSmall = NULL;
2344static HICON g_hOrigIcon = NULL;
2345static HICON g_hVimIcon = NULL;
2346static BOOL g_fCanChangeIcon = FALSE;
2347
2348/* ICON* are not defined in VC++ 4.0 */
2349#ifndef ICON_SMALL
2350#define ICON_SMALL 0
2351#endif
2352#ifndef ICON_BIG
2353#define ICON_BIG 1
2354#endif
2355/*
2356 * GetConsoleIcon()
2357 * Description:
2358 * Attempts to retrieve the small icon and/or the big icon currently in
2359 * use by a given window.
2360 * Returns:
2361 * TRUE on success
2362 */
2363 static BOOL
2364GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002365 HWND hWnd,
2366 HICON *phIconSmall,
2367 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368{
2369 if (hWnd == NULL)
2370 return FALSE;
2371
2372 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002373 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2374 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002376 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2377 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378 return TRUE;
2379}
2380
2381/*
2382 * SetConsoleIcon()
2383 * Description:
2384 * Attempts to change the small icon and/or the big icon currently in
2385 * use by a given window.
2386 * Returns:
2387 * TRUE on success
2388 */
2389 static BOOL
2390SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002391 HWND hWnd,
2392 HICON hIconSmall,
2393 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002395 HICON hPrevIconSmall;
2396 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002397
2398 if (hWnd == NULL)
2399 return FALSE;
2400
2401 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002402 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2403 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002404 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002405 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2406 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002407 return TRUE;
2408}
2409
2410/*
2411 * SaveConsoleTitleAndIcon()
2412 * Description:
2413 * Saves the current console window title in g_szOrigTitle, for later
2414 * restoration. Also, attempts to obtain a handle to the console window,
2415 * and use it to save the small and big icons currently in use by the
2416 * console window. This is not always possible on some versions of Windows;
2417 * nor is it possible when running Vim remotely using Telnet (since the
2418 * console window the user sees is owned by a remote process).
2419 */
2420 static void
2421SaveConsoleTitleAndIcon(void)
2422{
2423 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2424
2425 /* Save the original title. */
2426 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2427 return;
2428
2429 /*
2430 * Obtain a handle to the console window using GetConsoleWindow() from
2431 * KERNEL32.DLL; we need to handle in order to change the window icon.
2432 * This function only exists on NT-based Windows, starting with Windows
2433 * 2000. On older operating systems, we can't change the window icon
2434 * anyway.
2435 */
2436 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2437 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2438 "GetConsoleWindow")) != NULL)
2439 {
2440 g_hWnd = (*GetConsoleWindowProc)();
2441 }
2442 if (g_hWnd == NULL)
2443 return;
2444
2445 /* Save the original console window icon. */
2446 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2447 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2448 return;
2449
2450 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002451 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
2452 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002453 if (g_hVimIcon != NULL)
2454 g_fCanChangeIcon = TRUE;
2455}
2456#endif
2457
2458static int g_fWindInitCalled = FALSE;
2459static int g_fTermcapMode = FALSE;
2460static CONSOLE_CURSOR_INFO g_cci;
2461static DWORD g_cmodein = 0;
2462static DWORD g_cmodeout = 0;
2463
2464/*
2465 * non-GUI version of mch_init().
2466 */
2467 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002468mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002469{
2470#ifndef FEAT_RESTORE_ORIG_SCREEN
2471 CONSOLE_SCREEN_BUFFER_INFO csbi;
2472#endif
2473#ifndef __MINGW32__
2474 extern int _fmode;
2475#endif
2476
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002477 /* Silently handle invalid parameters to CRT functions */
2478 SET_INVALID_PARAM_HANDLER;
2479
Bram Moolenaar071d4272004-06-13 20:20:40 +00002480 /* Let critical errors result in a failure, not in a dialog box. Required
2481 * for the timestamp test to work on removed floppies. */
2482 SetErrorMode(SEM_FAILCRITICALERRORS);
2483
2484 _fmode = O_BINARY; /* we do our own CR-LF translation */
2485 out_flush();
2486
2487 /* Obtain handles for the standard Console I/O devices */
2488 if (read_cmd_fd == 0)
2489 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2490 else
2491 create_conin();
2492 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2493
2494#ifdef FEAT_RESTORE_ORIG_SCREEN
2495 /* Save the initial console buffer for later restoration */
2496 SaveConsoleBuffer(&g_cbOrig);
2497 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2498#else
2499 /* Get current text attributes */
2500 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2501 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2502#endif
2503 if (cterm_normal_fg_color == 0)
2504 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2505 if (cterm_normal_bg_color == 0)
2506 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2507
2508 /* set termcap codes to current text attributes */
2509 update_tcap(g_attrCurrent);
2510
2511 GetConsoleCursorInfo(g_hConOut, &g_cci);
2512 GetConsoleMode(g_hConIn, &g_cmodein);
2513 GetConsoleMode(g_hConOut, &g_cmodeout);
2514
2515#ifdef FEAT_TITLE
2516 SaveConsoleTitleAndIcon();
2517 /*
2518 * Set both the small and big icons of the console window to Vim's icon.
2519 * Note that Vim presently only has one size of icon (32x32), but it
2520 * automatically gets scaled down to 16x16 when setting the small icon.
2521 */
2522 if (g_fCanChangeIcon)
2523 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2524#endif
2525
2526 ui_get_shellsize();
2527
2528#ifdef MCH_WRITE_DUMP
2529 fdDump = fopen("dump", "wt");
2530
2531 if (fdDump)
2532 {
2533 time_t t;
2534
2535 time(&t);
2536 fputs(ctime(&t), fdDump);
2537 fflush(fdDump);
2538 }
2539#endif
2540
2541 g_fWindInitCalled = TRUE;
2542
2543#ifdef FEAT_MOUSE
2544 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2545#endif
2546
2547#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002548 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002549#endif
2550
2551 /* This will be NULL on anything but NT 4.0 */
2552 s_pfnGetConsoleKeyboardLayoutName =
2553 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2554 "GetConsoleKeyboardLayoutNameA");
2555}
2556
2557/*
2558 * non-GUI version of mch_exit().
2559 * Shut down and exit with status `r'
2560 * Careful: mch_exit() may be called before mch_init()!
2561 */
2562 void
2563mch_exit(int r)
2564{
2565 stoptermcap();
2566
2567 if (g_fWindInitCalled)
2568 settmode(TMODE_COOK);
2569
2570 ml_close_all(TRUE); /* remove all memfiles */
2571
2572 if (g_fWindInitCalled)
2573 {
2574#ifdef FEAT_TITLE
2575 mch_restore_title(3);
2576 /*
2577 * Restore both the small and big icons of the console window to
2578 * what they were at startup. Don't do this when the window is
2579 * closed, Vim would hang here.
2580 */
2581 if (g_fCanChangeIcon && !g_fForceExit)
2582 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2583#endif
2584
2585#ifdef MCH_WRITE_DUMP
2586 if (fdDump)
2587 {
2588 time_t t;
2589
2590 time(&t);
2591 fputs(ctime(&t), fdDump);
2592 fclose(fdDump);
2593 }
2594 fdDump = NULL;
2595#endif
2596 }
2597
2598 SetConsoleCursorInfo(g_hConOut, &g_cci);
2599 SetConsoleMode(g_hConIn, g_cmodein);
2600 SetConsoleMode(g_hConOut, g_cmodeout);
2601
2602#ifdef DYNAMIC_GETTEXT
2603 dyn_libintl_end();
2604#endif
2605
2606 exit(r);
2607}
2608#endif /* !FEAT_GUI_W32 */
2609
Bram Moolenaar071d4272004-06-13 20:20:40 +00002610/*
2611 * Do we have an interactive window?
2612 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002613/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002614 int
2615mch_check_win(
2616 int argc,
2617 char **argv)
2618{
2619 get_exe_name();
2620
2621#ifdef FEAT_GUI_W32
2622 return OK; /* GUI always has a tty */
2623#else
2624 if (isatty(1))
2625 return OK;
2626 return FAIL;
2627#endif
2628}
2629
2630
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002631#ifdef FEAT_MBYTE
2632/*
2633 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2634 * if it already exists. When "len" is > 0, also expand short to long
2635 * filenames.
2636 * Return FAIL if wide functions are not available, OK otherwise.
2637 * NOTE: much of this is identical to fname_case(), keep in sync!
2638 */
2639 static int
2640fname_casew(
2641 WCHAR *name,
2642 int len)
2643{
2644 WCHAR szTrueName[_MAX_PATH + 2];
2645 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2646 WCHAR *ptrue, *ptruePrev;
2647 WCHAR *porig, *porigPrev;
2648 int flen;
2649 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002650 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002651 int c;
2652 int slen;
2653
2654 flen = (int)wcslen(name);
2655 if (flen > _MAX_PATH)
2656 return OK;
2657
2658 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2659
2660 /* Build the new name in szTrueName[] one component at a time. */
2661 porig = name;
2662 ptrue = szTrueName;
2663
2664 if (iswalpha(porig[0]) && porig[1] == L':')
2665 {
2666 /* copy leading drive letter */
2667 *ptrue++ = *porig++;
2668 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002669 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002670 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002671
2672 while (*porig != NUL)
2673 {
2674 /* copy \ characters */
2675 while (*porig == psepc)
2676 *ptrue++ = *porig++;
2677
2678 ptruePrev = ptrue;
2679 porigPrev = porig;
2680 while (*porig != NUL && *porig != psepc)
2681 {
2682 *ptrue++ = *porig++;
2683 }
2684 *ptrue = NUL;
2685
2686 /* To avoid a slow failure append "\*" when searching a directory,
2687 * server or network share. */
2688 wcscpy(szTrueNameTemp, szTrueName);
2689 slen = (int)wcslen(szTrueNameTemp);
2690 if (*porig == psepc && slen + 2 < _MAX_PATH)
2691 wcscpy(szTrueNameTemp + slen, L"\\*");
2692
2693 /* Skip "", "." and "..". */
2694 if (ptrue > ptruePrev
2695 && (ptruePrev[0] != L'.'
2696 || (ptruePrev[1] != NUL
2697 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2698 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2699 != INVALID_HANDLE_VALUE)
2700 {
2701 c = *porig;
2702 *porig = NUL;
2703
2704 /* Only use the match when it's the same name (ignoring case) or
2705 * expansion is allowed and there is a match with the short name
2706 * and there is enough room. */
2707 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2708 || (len > 0
2709 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2710 && (int)(ptruePrev - szTrueName)
2711 + (int)wcslen(fb.cFileName) < len)))
2712 {
2713 wcscpy(ptruePrev, fb.cFileName);
2714
2715 /* Look for exact match and prefer it if found. Must be a
2716 * long name, otherwise there would be only one match. */
2717 while (FindNextFileW(hFind, &fb))
2718 {
2719 if (*fb.cAlternateFileName != NUL
2720 && (wcscoll(porigPrev, fb.cFileName) == 0
2721 || (len > 0
2722 && (_wcsicoll(porigPrev,
2723 fb.cAlternateFileName) == 0
2724 && (int)(ptruePrev - szTrueName)
2725 + (int)wcslen(fb.cFileName) < len))))
2726 {
2727 wcscpy(ptruePrev, fb.cFileName);
2728 break;
2729 }
2730 }
2731 }
2732 FindClose(hFind);
2733 *porig = c;
2734 ptrue = ptruePrev + wcslen(ptruePrev);
2735 }
2736 else if (hFind == INVALID_HANDLE_VALUE
2737 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2738 return FAIL;
2739 }
2740
2741 wcscpy(name, szTrueName);
2742 return OK;
2743}
2744#endif
2745
Bram Moolenaar071d4272004-06-13 20:20:40 +00002746/*
2747 * fname_case(): Set the case of the file name, if it already exists.
2748 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002749 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002750 */
2751 void
2752fname_case(
2753 char_u *name,
2754 int len)
2755{
2756 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002757 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002758 char *ptrue, *ptruePrev;
2759 char *porig, *porigPrev;
2760 int flen;
2761 WIN32_FIND_DATA fb;
2762 HANDLE hFind;
2763 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002764 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002765
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002766 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002767 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002768 return;
2769
2770 slash_adjust(name);
2771
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002772#ifdef FEAT_MBYTE
2773 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2774 {
2775 WCHAR *p = enc_to_utf16(name, NULL);
2776
2777 if (p != NULL)
2778 {
2779 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002780 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002781
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002782 wcsncpy(buf, p, _MAX_PATH);
2783 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002784 vim_free(p);
2785
2786 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2787 {
2788 q = utf16_to_enc(buf, NULL);
2789 if (q != NULL)
2790 {
2791 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2792 vim_free(q);
2793 return;
2794 }
2795 }
2796 }
2797 /* Retry with non-wide function (for Windows 98). */
2798 }
2799#endif
2800
2801 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2802 * So we should check this after calling wide function. */
2803 if (flen > _MAX_PATH)
2804 return;
2805
Bram Moolenaar071d4272004-06-13 20:20:40 +00002806 /* Build the new name in szTrueName[] one component at a time. */
2807 porig = name;
2808 ptrue = szTrueName;
2809
2810 if (isalpha(porig[0]) && porig[1] == ':')
2811 {
2812 /* copy leading drive letter */
2813 *ptrue++ = *porig++;
2814 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002815 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002816 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002817
2818 while (*porig != NUL)
2819 {
2820 /* copy \ characters */
2821 while (*porig == psepc)
2822 *ptrue++ = *porig++;
2823
2824 ptruePrev = ptrue;
2825 porigPrev = porig;
2826 while (*porig != NUL && *porig != psepc)
2827 {
2828#ifdef FEAT_MBYTE
2829 int l;
2830
2831 if (enc_dbcs)
2832 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002833 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002834 while (--l >= 0)
2835 *ptrue++ = *porig++;
2836 }
2837 else
2838#endif
2839 *ptrue++ = *porig++;
2840 }
2841 *ptrue = NUL;
2842
Bram Moolenaar464c9252010-10-13 20:37:41 +02002843 /* To avoid a slow failure append "\*" when searching a directory,
2844 * server or network share. */
2845 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002846 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002847 if (*porig == psepc && slen + 2 < _MAX_PATH)
2848 STRCPY(szTrueNameTemp + slen, "\\*");
2849
Bram Moolenaar071d4272004-06-13 20:20:40 +00002850 /* Skip "", "." and "..". */
2851 if (ptrue > ptruePrev
2852 && (ptruePrev[0] != '.'
2853 || (ptruePrev[1] != NUL
2854 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002855 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856 != INVALID_HANDLE_VALUE)
2857 {
2858 c = *porig;
2859 *porig = NUL;
2860
2861 /* Only use the match when it's the same name (ignoring case) or
2862 * expansion is allowed and there is a match with the short name
2863 * and there is enough room. */
2864 if (_stricoll(porigPrev, fb.cFileName) == 0
2865 || (len > 0
2866 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2867 && (int)(ptruePrev - szTrueName)
2868 + (int)strlen(fb.cFileName) < len)))
2869 {
2870 STRCPY(ptruePrev, fb.cFileName);
2871
2872 /* Look for exact match and prefer it if found. Must be a
2873 * long name, otherwise there would be only one match. */
2874 while (FindNextFile(hFind, &fb))
2875 {
2876 if (*fb.cAlternateFileName != NUL
2877 && (strcoll(porigPrev, fb.cFileName) == 0
2878 || (len > 0
2879 && (_stricoll(porigPrev,
2880 fb.cAlternateFileName) == 0
2881 && (int)(ptruePrev - szTrueName)
2882 + (int)strlen(fb.cFileName) < len))))
2883 {
2884 STRCPY(ptruePrev, fb.cFileName);
2885 break;
2886 }
2887 }
2888 }
2889 FindClose(hFind);
2890 *porig = c;
2891 ptrue = ptruePrev + strlen(ptruePrev);
2892 }
2893 }
2894
2895 STRCPY(name, szTrueName);
2896}
2897
2898
2899/*
2900 * Insert user name in s[len].
2901 */
2902 int
2903mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002904 char_u *s,
2905 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002906{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002907 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002908 DWORD cch = sizeof szUserName;
2909
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002910#ifdef FEAT_MBYTE
2911 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2912 {
2913 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2914 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2915
2916 if (GetUserNameW(wszUserName, &wcch))
2917 {
2918 char_u *p = utf16_to_enc(wszUserName, NULL);
2919
2920 if (p != NULL)
2921 {
2922 vim_strncpy(s, p, len - 1);
2923 vim_free(p);
2924 return OK;
2925 }
2926 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002927 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2928 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002929 /* Retry with non-wide function (for Windows 98). */
2930 }
2931#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932 if (GetUserName(szUserName, &cch))
2933 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002934 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 return OK;
2936 }
2937 s[0] = NUL;
2938 return FAIL;
2939}
2940
2941
2942/*
2943 * Insert host name in s[len].
2944 */
2945 void
2946mch_get_host_name(
2947 char_u *s,
2948 int len)
2949{
2950 DWORD cch = len;
2951
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002952#ifdef FEAT_MBYTE
2953 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2954 {
2955 WCHAR wszHostName[256 + 1];
2956 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2957
2958 if (GetComputerNameW(wszHostName, &wcch))
2959 {
2960 char_u *p = utf16_to_enc(wszHostName, NULL);
2961
2962 if (p != NULL)
2963 {
2964 vim_strncpy(s, p, len - 1);
2965 vim_free(p);
2966 return;
2967 }
2968 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002969 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2970 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002971 /* Retry with non-wide function (for Windows 98). */
2972 }
2973#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002975 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002976}
2977
2978
2979/*
2980 * return process ID
2981 */
2982 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002983mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984{
2985 return (long)GetCurrentProcessId();
2986}
2987
2988
2989/*
2990 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2991 * Return OK for success, FAIL for failure.
2992 */
2993 int
2994mch_dirname(
2995 char_u *buf,
2996 int len)
2997{
2998 /*
2999 * Originally this was:
3000 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3001 * But the Win32s known bug list says that getcwd() doesn't work
3002 * so use the Win32 system call instead. <Negri>
3003 */
3004#ifdef FEAT_MBYTE
3005 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3006 {
3007 WCHAR wbuf[_MAX_PATH + 1];
3008
3009 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3010 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003011 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012
3013 if (p != NULL)
3014 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003015 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003016 vim_free(p);
3017 return OK;
3018 }
3019 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003020 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3021 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003022 /* Retry with non-wide function (for Windows 98). */
3023 }
3024#endif
3025 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
3026}
3027
3028/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003029 * Get file permissions for "name".
3030 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031 */
3032 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003033mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003034{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003035 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003036 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003038 n = mch_stat(name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003039 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040}
3041
3042
3043/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003044 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003045 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003046 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003047 */
3048 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003049mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003050{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003051 long n = -1;
3052
Bram Moolenaar071d4272004-06-13 20:20:40 +00003053#ifdef FEAT_MBYTE
3054 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3055 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003056 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057
3058 if (p != NULL)
3059 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003060 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003062 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003063 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064 /* Retry with non-wide function (for Windows 98). */
3065 }
3066 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003067 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003069 n = _chmod(name, perm);
3070 if (n == -1)
3071 return FAIL;
3072
3073 win32_set_archive(name);
3074
3075 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003076}
3077
3078/*
3079 * Set hidden flag for "name".
3080 */
3081 void
3082mch_hide(char_u *name)
3083{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003084 int attrs = win32_getattrs(name);
3085 if (attrs == -1)
3086 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003087
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003088 attrs |= FILE_ATTRIBUTE_HIDDEN;
3089 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090}
3091
3092/*
3093 * return TRUE if "name" is a directory
3094 * return FALSE if "name" is not a directory or upon error
3095 */
3096 int
3097mch_isdir(char_u *name)
3098{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003099 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003100
3101 if (f == -1)
3102 return FALSE; /* file does not exist at all */
3103
3104 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3105}
3106
3107/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003108 * Create directory "name".
3109 * Return 0 on success, -1 on error.
3110 */
3111 int
3112mch_mkdir(char_u *name)
3113{
3114#ifdef FEAT_MBYTE
3115 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3116 {
3117 WCHAR *p;
3118 int retval;
3119
3120 p = enc_to_utf16(name, NULL);
3121 if (p == NULL)
3122 return -1;
3123 retval = _wmkdir(p);
3124 vim_free(p);
3125 return retval;
3126 }
3127#endif
3128 return _mkdir(name);
3129}
3130
3131/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003132 * Return TRUE if file "fname" has more than one link.
3133 */
3134 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003135mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003136{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003137 BY_HANDLE_FILE_INFORMATION info;
3138
3139 return win32_fileinfo(fname, &info) == FILEINFO_OK
3140 && info.nNumberOfLinks > 1;
3141}
3142
3143/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003144 * Return TRUE if file "fname" is a symbolic link.
3145 */
3146 int
3147mch_is_symbolic_link(char_u *fname)
3148{
3149 HANDLE hFind;
3150 int res = FALSE;
3151 WIN32_FIND_DATAA findDataA;
3152 DWORD fileFlags = 0, reparseTag = 0;
3153#ifdef FEAT_MBYTE
3154 WCHAR *wn = NULL;
3155 WIN32_FIND_DATAW findDataW;
3156
3157 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3158 wn = enc_to_utf16(fname, NULL);
3159 if (wn != NULL)
3160 {
3161 hFind = FindFirstFileW(wn, &findDataW);
3162 vim_free(wn);
3163 if (hFind == INVALID_HANDLE_VALUE
3164 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3165 {
3166 /* Retry with non-wide function (for Windows 98). */
3167 hFind = FindFirstFile(fname, &findDataA);
3168 if (hFind != INVALID_HANDLE_VALUE)
3169 {
3170 fileFlags = findDataA.dwFileAttributes;
3171 reparseTag = findDataA.dwReserved0;
3172 }
3173 }
3174 else
3175 {
3176 fileFlags = findDataW.dwFileAttributes;
3177 reparseTag = findDataW.dwReserved0;
3178 }
3179 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003180 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003181#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003182 {
3183 hFind = FindFirstFile(fname, &findDataA);
3184 if (hFind != INVALID_HANDLE_VALUE)
3185 {
3186 fileFlags = findDataA.dwFileAttributes;
3187 reparseTag = findDataA.dwReserved0;
3188 }
3189 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003190
3191 if (hFind != INVALID_HANDLE_VALUE)
3192 FindClose(hFind);
3193
3194 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3195 && reparseTag == IO_REPARSE_TAG_SYMLINK)
3196 res = TRUE;
3197
3198 return res;
3199}
3200
3201/*
3202 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3203 * link.
3204 */
3205 int
3206mch_is_linked(char_u *fname)
3207{
3208 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3209 return TRUE;
3210 return FALSE;
3211}
3212
3213/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003214 * Get the by-handle-file-information for "fname".
3215 * Returns FILEINFO_OK when OK.
3216 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3217 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3218 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3219 */
3220 int
3221win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3222{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003223 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003224 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003225#ifdef FEAT_MBYTE
3226 WCHAR *wn = NULL;
3227
3228 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003229 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003230 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003231 if (wn == NULL)
3232 res = FILEINFO_ENC_FAIL;
3233 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003234 if (wn != NULL)
3235 {
3236 hFile = CreateFileW(wn, /* file name */
3237 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003238 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003239 NULL, /* security descriptor */
3240 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003241 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003242 NULL); /* handle to template file */
3243 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003244 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003245 {
3246 /* Retry with non-wide function (for Windows 98). */
3247 vim_free(wn);
3248 wn = NULL;
3249 }
3250 }
3251 if (wn == NULL)
3252#endif
3253 hFile = CreateFile(fname, /* file name */
3254 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003255 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003256 NULL, /* security descriptor */
3257 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003258 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003259 NULL); /* handle to template file */
3260
3261 if (hFile != INVALID_HANDLE_VALUE)
3262 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003263 if (GetFileInformationByHandle(hFile, info) != 0)
3264 res = FILEINFO_OK;
3265 else
3266 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003267 CloseHandle(hFile);
3268 }
3269
3270#ifdef FEAT_MBYTE
3271 vim_free(wn);
3272#endif
3273 return res;
3274}
3275
3276/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003277 * get file attributes for `name'
3278 * -1 : error
3279 * else FILE_ATTRIBUTE_* defined in winnt.h
3280 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003281 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003282win32_getattrs(char_u *name)
3283{
3284 int attr;
3285#ifdef FEAT_MBYTE
3286 WCHAR *p = NULL;
3287
3288 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3289 p = enc_to_utf16(name, NULL);
3290
3291 if (p != NULL)
3292 {
3293 attr = GetFileAttributesW(p);
3294 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3295 {
3296 /* Retry with non-wide function (for Windows 98). */
3297 vim_free(p);
3298 p = NULL;
3299 }
3300 }
3301 if (p == NULL)
3302#endif
3303 attr = GetFileAttributes((char *)name);
3304#ifdef FEAT_MBYTE
3305 vim_free(p);
3306#endif
3307 return attr;
3308}
3309
3310/*
3311 * set file attributes for `name' to `attrs'
3312 *
3313 * return -1 for failure, 0 otherwise
3314 */
3315 static
3316 int
3317win32_setattrs(char_u *name, int attrs)
3318{
3319 int res;
3320#ifdef FEAT_MBYTE
3321 WCHAR *p = NULL;
3322
3323 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3324 p = enc_to_utf16(name, NULL);
3325
3326 if (p != NULL)
3327 {
3328 res = SetFileAttributesW(p, attrs);
3329 if (res == FALSE
3330 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3331 {
3332 /* Retry with non-wide function (for Windows 98). */
3333 vim_free(p);
3334 p = NULL;
3335 }
3336 }
3337 if (p == NULL)
3338#endif
3339 res = SetFileAttributes((char *)name, attrs);
3340#ifdef FEAT_MBYTE
3341 vim_free(p);
3342#endif
3343 return res ? 0 : -1;
3344}
3345
3346/*
3347 * Set archive flag for "name".
3348 */
3349 static
3350 int
3351win32_set_archive(char_u *name)
3352{
3353 int attrs = win32_getattrs(name);
3354 if (attrs == -1)
3355 return -1;
3356
3357 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3358 return win32_setattrs(name, attrs);
3359}
3360
3361/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003362 * Return TRUE if file or directory "name" is writable (not readonly).
3363 * Strange semantics of Win32: a readonly directory is writable, but you can't
3364 * delete a file. Let's say this means it is writable.
3365 */
3366 int
3367mch_writable(char_u *name)
3368{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003369 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003370
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003371 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3372 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003373}
3374
Bram Moolenaar071d4272004-06-13 20:20:40 +00003375/*
3376 * Return 1 if "name" can be executed, 0 if not.
3377 * Return -1 if unknown.
3378 */
3379 int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003380mch_can_exe(char_u *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003381{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003382 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003383 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003384 char_u *p;
3385
3386 if (len >= _MAX_PATH) /* safety check */
3387 return FALSE;
3388
3389 /* If there already is an extension try using the name directly. Also do
3390 * this with a Unix-shell like 'shell'. */
3391 if (vim_strchr(gettail(name), '.') != NULL
3392 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003393 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003394 return TRUE;
3395
3396 /*
3397 * Loop over all extensions in $PATHEXT.
3398 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003399 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003400 p = mch_getenv("PATHEXT");
3401 if (p == NULL)
3402 p = (char_u *)".com;.exe;.bat;.cmd";
3403 while (*p)
3404 {
3405 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3406 {
3407 /* A single "." means no extension is added. */
3408 buf[len] = NUL;
3409 ++p;
3410 if (*p)
3411 ++p;
3412 }
3413 else
3414 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003415 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003416 return TRUE;
3417 }
3418 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003419}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003420
3421/*
3422 * Check what "name" is:
3423 * NODE_NORMAL: file or directory (or doesn't exist)
3424 * NODE_WRITABLE: writable device, socket, fifo, etc.
3425 * NODE_OTHER: non-writable things
3426 */
3427 int
3428mch_nodetype(char_u *name)
3429{
3430 HANDLE hFile;
3431 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003432#ifdef FEAT_MBYTE
3433 WCHAR *wn = NULL;
3434#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003435
Bram Moolenaar043545e2006-10-10 16:44:07 +00003436 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3437 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3438 * here. */
3439 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3440 return NODE_WRITABLE;
3441
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003442#ifdef FEAT_MBYTE
3443 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3444 {
3445 wn = enc_to_utf16(name, NULL);
3446 if (wn != NULL)
3447 {
3448 hFile = CreateFileW(wn, /* file name */
3449 GENERIC_WRITE, /* access mode */
3450 0, /* share mode */
3451 NULL, /* security descriptor */
3452 OPEN_EXISTING, /* creation disposition */
3453 0, /* file attributes */
3454 NULL); /* handle to template file */
3455 if (hFile == INVALID_HANDLE_VALUE
3456 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3457 {
3458 /* Retry with non-wide function (for Windows 98). */
3459 vim_free(wn);
3460 wn = NULL;
3461 }
3462 }
3463 }
3464 if (wn == NULL)
3465#endif
3466 hFile = CreateFile(name, /* file name */
3467 GENERIC_WRITE, /* access mode */
3468 0, /* share mode */
3469 NULL, /* security descriptor */
3470 OPEN_EXISTING, /* creation disposition */
3471 0, /* file attributes */
3472 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003473
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003474#ifdef FEAT_MBYTE
3475 vim_free(wn);
3476#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003477 if (hFile == INVALID_HANDLE_VALUE)
3478 return NODE_NORMAL;
3479
3480 type = GetFileType(hFile);
3481 CloseHandle(hFile);
3482 if (type == FILE_TYPE_CHAR)
3483 return NODE_WRITABLE;
3484 if (type == FILE_TYPE_DISK)
3485 return NODE_NORMAL;
3486 return NODE_OTHER;
3487}
3488
3489#ifdef HAVE_ACL
3490struct my_acl
3491{
3492 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3493 PSID pSidOwner;
3494 PSID pSidGroup;
3495 PACL pDacl;
3496 PACL pSacl;
3497};
3498#endif
3499
3500/*
3501 * Return a pointer to the ACL of file "fname" in allocated memory.
3502 * Return NULL if the ACL is not available for whatever reason.
3503 */
3504 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003505mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506{
3507#ifndef HAVE_ACL
3508 return (vim_acl_T)NULL;
3509#else
3510 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003511 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003512
3513 /* This only works on Windows NT and 2000. */
3514 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3515 {
3516 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3517 if (p != NULL)
3518 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003519# ifdef FEAT_MBYTE
3520 WCHAR *wn = NULL;
3521
3522 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3523 wn = enc_to_utf16(fname, NULL);
3524 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003525 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003526 /* Try to retrieve the entire security descriptor. */
3527 err = pGetNamedSecurityInfoW(
3528 wn, // 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)pGetNamedSecurityInfoW(
3544 wn,
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;
3557 }
3558 vim_free(wn);
3559 }
3560 else
3561# endif
3562 {
3563 /* Try to retrieve the entire security descriptor. */
3564 err = pGetNamedSecurityInfo(
3565 (LPSTR)fname, // Abstract filename
3566 SE_FILE_OBJECT, // File Object
3567 OWNER_SECURITY_INFORMATION |
3568 GROUP_SECURITY_INFORMATION |
3569 DACL_SECURITY_INFORMATION |
3570 SACL_SECURITY_INFORMATION,
3571 &p->pSidOwner, // Ownership information.
3572 &p->pSidGroup, // Group membership.
3573 &p->pDacl, // Discretionary information.
3574 &p->pSacl, // For auditing purposes.
3575 &p->pSecurityDescriptor);
3576 if (err == ERROR_ACCESS_DENIED ||
3577 err == ERROR_PRIVILEGE_NOT_HELD)
3578 {
3579 /* Retrieve only DACL. */
3580 (void)pGetNamedSecurityInfo(
3581 (LPSTR)fname,
3582 SE_FILE_OBJECT,
3583 DACL_SECURITY_INFORMATION,
3584 NULL,
3585 NULL,
3586 &p->pDacl,
3587 NULL,
3588 &p->pSecurityDescriptor);
3589 }
3590 if (p->pSecurityDescriptor == NULL)
3591 {
3592 mch_free_acl((vim_acl_T)p);
3593 p = NULL;
3594 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595 }
3596 }
3597 }
3598
3599 return (vim_acl_T)p;
3600#endif
3601}
3602
Bram Moolenaar27515922013-06-29 15:36:26 +02003603#ifdef HAVE_ACL
3604/*
3605 * Check if "acl" contains inherited ACE.
3606 */
3607 static BOOL
3608is_acl_inherited(PACL acl)
3609{
3610 DWORD i;
3611 ACL_SIZE_INFORMATION acl_info;
3612 PACCESS_ALLOWED_ACE ace;
3613
3614 acl_info.AceCount = 0;
3615 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3616 for (i = 0; i < acl_info.AceCount; i++)
3617 {
3618 GetAce(acl, i, (LPVOID *)&ace);
3619 if (ace->Header.AceFlags & INHERITED_ACE)
3620 return TRUE;
3621 }
3622 return FALSE;
3623}
3624#endif
3625
Bram Moolenaar071d4272004-06-13 20:20:40 +00003626/*
3627 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3628 * Errors are ignored.
3629 * This must only be called with "acl" equal to what mch_get_acl() returned.
3630 */
3631 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003632mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003633{
3634#ifdef HAVE_ACL
3635 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003636 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003637
3638 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003639 {
3640# ifdef FEAT_MBYTE
3641 WCHAR *wn = NULL;
3642# endif
3643
3644 /* Set security flags */
3645 if (p->pSidOwner)
3646 sec_info |= OWNER_SECURITY_INFORMATION;
3647 if (p->pSidGroup)
3648 sec_info |= GROUP_SECURITY_INFORMATION;
3649 if (p->pDacl)
3650 {
3651 sec_info |= DACL_SECURITY_INFORMATION;
3652 /* Do not inherit its parent's DACL.
3653 * If the DACL is inherited, Cygwin permissions would be changed.
3654 */
3655 if (!is_acl_inherited(p->pDacl))
3656 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3657 }
3658 if (p->pSacl)
3659 sec_info |= SACL_SECURITY_INFORMATION;
3660
3661# ifdef FEAT_MBYTE
3662 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3663 wn = enc_to_utf16(fname, NULL);
3664 if (wn != NULL)
3665 {
3666 (void)pSetNamedSecurityInfoW(
3667 wn, // Abstract filename
3668 SE_FILE_OBJECT, // File Object
3669 sec_info,
3670 p->pSidOwner, // Ownership information.
3671 p->pSidGroup, // Group membership.
3672 p->pDacl, // Discretionary information.
3673 p->pSacl // For auditing purposes.
3674 );
3675 vim_free(wn);
3676 }
3677 else
3678# endif
3679 {
3680 (void)pSetNamedSecurityInfo(
3681 (LPSTR)fname, // Abstract filename
3682 SE_FILE_OBJECT, // File Object
3683 sec_info,
3684 p->pSidOwner, // Ownership information.
3685 p->pSidGroup, // Group membership.
3686 p->pDacl, // Discretionary information.
3687 p->pSacl // For auditing purposes.
3688 );
3689 }
3690 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003691#endif
3692}
3693
3694 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003695mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003696{
3697#ifdef HAVE_ACL
3698 struct my_acl *p = (struct my_acl *)acl;
3699
3700 if (p != NULL)
3701 {
3702 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3703 vim_free(p);
3704 }
3705#endif
3706}
3707
3708#ifndef FEAT_GUI_W32
3709
3710/*
3711 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3712 */
3713 static BOOL WINAPI
3714handler_routine(
3715 DWORD dwCtrlType)
3716{
3717 switch (dwCtrlType)
3718 {
3719 case CTRL_C_EVENT:
3720 if (ctrl_c_interrupts)
3721 g_fCtrlCPressed = TRUE;
3722 return TRUE;
3723
3724 case CTRL_BREAK_EVENT:
3725 g_fCBrkPressed = TRUE;
3726 return TRUE;
3727
3728 /* fatal events: shut down gracefully */
3729 case CTRL_CLOSE_EVENT:
3730 case CTRL_LOGOFF_EVENT:
3731 case CTRL_SHUTDOWN_EVENT:
3732 windgoto((int)Rows - 1, 0);
3733 g_fForceExit = TRUE;
3734
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003735 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736 (dwCtrlType == CTRL_CLOSE_EVENT
3737 ? _("close")
3738 : dwCtrlType == CTRL_LOGOFF_EVENT
3739 ? _("logoff")
3740 : _("shutdown")));
3741#ifdef DEBUG
3742 OutputDebugString(IObuff);
3743#endif
3744
3745 preserve_exit(); /* output IObuff, preserve files and exit */
3746
3747 return TRUE; /* not reached */
3748
3749 default:
3750 return FALSE;
3751 }
3752}
3753
3754
3755/*
3756 * set the tty in (raw) ? "raw" : "cooked" mode
3757 */
3758 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003759mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003760{
3761 DWORD cmodein;
3762 DWORD cmodeout;
3763 BOOL bEnableHandler;
3764
3765 GetConsoleMode(g_hConIn, &cmodein);
3766 GetConsoleMode(g_hConOut, &cmodeout);
3767 if (tmode == TMODE_RAW)
3768 {
3769 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3770 ENABLE_ECHO_INPUT);
3771#ifdef FEAT_MOUSE
3772 if (g_fMouseActive)
3773 cmodein |= ENABLE_MOUSE_INPUT;
3774#endif
3775 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3776 bEnableHandler = TRUE;
3777 }
3778 else /* cooked */
3779 {
3780 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3781 ENABLE_ECHO_INPUT);
3782 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3783 bEnableHandler = FALSE;
3784 }
3785 SetConsoleMode(g_hConIn, cmodein);
3786 SetConsoleMode(g_hConOut, cmodeout);
3787 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3788
3789#ifdef MCH_WRITE_DUMP
3790 if (fdDump)
3791 {
3792 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3793 tmode == TMODE_RAW ? "raw" :
3794 tmode == TMODE_COOK ? "cooked" : "normal",
3795 cmodein, cmodeout);
3796 fflush(fdDump);
3797 }
3798#endif
3799}
3800
3801
3802/*
3803 * Get the size of the current window in `Rows' and `Columns'
3804 * Return OK when size could be determined, FAIL otherwise.
3805 */
3806 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003807mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808{
3809 CONSOLE_SCREEN_BUFFER_INFO csbi;
3810
3811 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3812 {
3813 /*
3814 * For some reason, we are trying to get the screen dimensions
3815 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3816 * variables are really intended to mean the size of Vim screen
3817 * while in termcap mode.
3818 */
3819 Rows = g_cbTermcap.Info.dwSize.Y;
3820 Columns = g_cbTermcap.Info.dwSize.X;
3821 }
3822 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3823 {
3824 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3825 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3826 }
3827 else
3828 {
3829 Rows = 25;
3830 Columns = 80;
3831 }
3832 return OK;
3833}
3834
3835/*
3836 * Set a console window to `xSize' * `ySize'
3837 */
3838 static void
3839ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003840 HANDLE hConsole,
3841 int xSize,
3842 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003843{
3844 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3845 SMALL_RECT srWindowRect; /* hold the new console size */
3846 COORD coordScreen;
3847
3848#ifdef MCH_WRITE_DUMP
3849 if (fdDump)
3850 {
3851 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3852 fflush(fdDump);
3853 }
3854#endif
3855
3856 /* get the largest size we can size the console window to */
3857 coordScreen = GetLargestConsoleWindowSize(hConsole);
3858
3859 /* define the new console window size and scroll position */
3860 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3861 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3862 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3863
3864 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3865 {
3866 int sx, sy;
3867
3868 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3869 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3870 if (sy < ySize || sx < xSize)
3871 {
3872 /*
3873 * Increasing number of lines/columns, do buffer first.
3874 * Use the maximal size in x and y direction.
3875 */
3876 if (sy < ySize)
3877 coordScreen.Y = ySize;
3878 else
3879 coordScreen.Y = sy;
3880 if (sx < xSize)
3881 coordScreen.X = xSize;
3882 else
3883 coordScreen.X = sx;
3884 SetConsoleScreenBufferSize(hConsole, coordScreen);
3885 }
3886 }
3887
3888 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3889 {
3890#ifdef MCH_WRITE_DUMP
3891 if (fdDump)
3892 {
3893 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3894 GetLastError());
3895 fflush(fdDump);
3896 }
3897#endif
3898 }
3899
3900 /* define the new console buffer size */
3901 coordScreen.X = xSize;
3902 coordScreen.Y = ySize;
3903
3904 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3905 {
3906#ifdef MCH_WRITE_DUMP
3907 if (fdDump)
3908 {
3909 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3910 GetLastError());
3911 fflush(fdDump);
3912 }
3913#endif
3914 }
3915}
3916
3917
3918/*
3919 * Set the console window to `Rows' * `Columns'
3920 */
3921 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003922mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923{
3924 COORD coordScreen;
3925
3926 /* Don't change window size while still starting up */
3927 if (suppress_winsize != 0)
3928 {
3929 suppress_winsize = 2;
3930 return;
3931 }
3932
3933 if (term_console)
3934 {
3935 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3936
3937 /* Clamp Rows and Columns to reasonable values */
3938 if (Rows > coordScreen.Y)
3939 Rows = coordScreen.Y;
3940 if (Columns > coordScreen.X)
3941 Columns = coordScreen.X;
3942
3943 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3944 }
3945}
3946
3947/*
3948 * Rows and/or Columns has changed.
3949 */
3950 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003951mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003952{
3953 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3954}
3955
3956
3957/*
3958 * Called when started up, to set the winsize that was delayed.
3959 */
3960 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003961mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003962{
3963 if (suppress_winsize == 2)
3964 {
3965 suppress_winsize = 0;
3966 mch_set_shellsize();
3967 shell_resized();
3968 }
3969 suppress_winsize = 0;
3970}
3971#endif /* FEAT_GUI_W32 */
3972
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003973 static BOOL
3974vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003975 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003976 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003977 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003978 STARTUPINFO *si,
3979 PROCESS_INFORMATION *pi)
3980{
3981# ifdef FEAT_MBYTE
3982 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3983 {
3984 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
3985
3986 if (wcmd != NULL)
3987 {
3988 BOOL ret;
3989 ret = CreateProcessW(
3990 NULL, /* Executable name */
3991 wcmd, /* Command to execute */
3992 NULL, /* Process security attributes */
3993 NULL, /* Thread security attributes */
3994 inherit_handles, /* Inherit handles */
3995 flags, /* Creation flags */
3996 NULL, /* Environment */
3997 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003998 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003999 pi); /* Process information */
4000 vim_free(wcmd);
4001 return ret;
4002 }
4003 }
4004#endif
4005 return CreateProcess(
4006 NULL, /* Executable name */
4007 cmd, /* Command to execute */
4008 NULL, /* Process security attributes */
4009 NULL, /* Thread security attributes */
4010 inherit_handles, /* Inherit handles */
4011 flags, /* Creation flags */
4012 NULL, /* Environment */
4013 NULL, /* Current directory */
4014 si, /* Startup information */
4015 pi); /* Process information */
4016}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004017
4018
4019#if defined(FEAT_GUI_W32) || defined(PROTO)
4020
4021/*
4022 * Specialised version of system() for Win32 GUI mode.
4023 * This version proceeds as follows:
4024 * 1. Create a console window for use by the subprocess
4025 * 2. Run the subprocess (it gets the allocated console by default)
4026 * 3. Wait for the subprocess to terminate and get its exit code
4027 * 4. Prompt the user to press a key to close the console window
4028 */
4029 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004030mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004031{
4032 STARTUPINFO si;
4033 PROCESS_INFORMATION pi;
4034 DWORD ret = 0;
4035 HWND hwnd = GetFocus();
4036
4037 si.cb = sizeof(si);
4038 si.lpReserved = NULL;
4039 si.lpDesktop = NULL;
4040 si.lpTitle = NULL;
4041 si.dwFlags = STARTF_USESHOWWINDOW;
4042 /*
4043 * It's nicer to run a filter command in a minimized window, but in
4044 * Windows 95 this makes the command MUCH slower. We can't do it under
4045 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004046 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004047 */
4048 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004049 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004050 else
4051 si.wShowWindow = SW_SHOWNORMAL;
4052 si.cbReserved2 = 0;
4053 si.lpReserved2 = NULL;
4054
4055 /* There is a strange error on Windows 95 when using "c:\\command.com".
4056 * When the "c:\\" is left out it works OK...? */
4057 if (mch_windows95()
4058 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4059 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4060 cmd += 3;
4061
4062 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004063 vim_create_process(cmd, FALSE,
4064 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004065
4066 /* Wait for the command to terminate before continuing */
4067 if (g_PlatformId != VER_PLATFORM_WIN32s)
4068 {
4069#ifdef FEAT_GUI
4070 int delay = 1;
4071
4072 /* Keep updating the window while waiting for the shell to finish. */
4073 for (;;)
4074 {
4075 MSG msg;
4076
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004077 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004078 {
4079 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004080 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004081 delay = 1;
4082 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004083 }
4084 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4085 break;
4086
4087 /* We start waiting for a very short time and then increase it, so
4088 * that we respond quickly when the process is quick, and don't
4089 * consume too much overhead when it's slow. */
4090 if (delay < 50)
4091 delay += 10;
4092 }
4093#else
4094 WaitForSingleObject(pi.hProcess, INFINITE);
4095#endif
4096
4097 /* Get the command exit code */
4098 GetExitCodeProcess(pi.hProcess, &ret);
4099 }
4100 else
4101 {
4102 /*
4103 * This ugly code is the only quick way of performing
4104 * a synchronous spawn under Win32s. Yuk.
4105 */
4106 num_windows = 0;
4107 EnumWindows(win32ssynch_cb, 0);
4108 old_num_windows = num_windows;
4109 do
4110 {
4111 Sleep(1000);
4112 num_windows = 0;
4113 EnumWindows(win32ssynch_cb, 0);
4114 } while (num_windows == old_num_windows);
4115 ret = 0;
4116 }
4117
4118 /* Close the handles to the subprocess, so that it goes away */
4119 CloseHandle(pi.hThread);
4120 CloseHandle(pi.hProcess);
4121
4122 /* Try to get input focus back. Doesn't always work though. */
4123 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4124
4125 return ret;
4126}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004127
4128/*
4129 * Thread launched by the gui to send the current buffer data to the
4130 * process. This way avoid to hang up vim totally if the children
4131 * process take a long time to process the lines.
4132 */
4133 static DWORD WINAPI
4134sub_process_writer(LPVOID param)
4135{
4136 HANDLE g_hChildStd_IN_Wr = param;
4137 linenr_T lnum = curbuf->b_op_start.lnum;
4138 DWORD len = 0;
4139 DWORD l;
4140 char_u *lp = ml_get(lnum);
4141 char_u *s;
4142 int written = 0;
4143
4144 for (;;)
4145 {
4146 l = (DWORD)STRLEN(lp + written);
4147 if (l == 0)
4148 len = 0;
4149 else if (lp[written] == NL)
4150 {
4151 /* NL -> NUL translation */
4152 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4153 }
4154 else
4155 {
4156 s = vim_strchr(lp + written, NL);
4157 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4158 s == NULL ? l : (DWORD)(s - (lp + written)),
4159 &len, NULL);
4160 }
4161 if (len == (int)l)
4162 {
4163 /* Finished a line, add a NL, unless this line should not have
4164 * one. */
4165 if (lnum != curbuf->b_op_end.lnum
4166 || !curbuf->b_p_bin
4167 || (lnum != curbuf->b_no_eol_lnum
4168 && (lnum != curbuf->b_ml.ml_line_count
4169 || curbuf->b_p_eol)))
4170 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004171 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004172 }
4173
4174 ++lnum;
4175 if (lnum > curbuf->b_op_end.lnum)
4176 break;
4177
4178 lp = ml_get(lnum);
4179 written = 0;
4180 }
4181 else if (len > 0)
4182 written += len;
4183 }
4184
4185 /* finished all the lines, close pipe */
4186 CloseHandle(g_hChildStd_IN_Wr);
4187 ExitThread(0);
4188}
4189
4190
4191# define BUFLEN 100 /* length for buffer, stolen from unix version */
4192
4193/*
4194 * This function read from the children's stdout and write the
4195 * data on screen or in the buffer accordingly.
4196 */
4197 static void
4198dump_pipe(int options,
4199 HANDLE g_hChildStd_OUT_Rd,
4200 garray_T *ga,
4201 char_u buffer[],
4202 DWORD *buffer_off)
4203{
4204 DWORD availableBytes = 0;
4205 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004206 int ret;
4207 DWORD len;
4208 DWORD toRead;
4209 int repeatCount;
4210
4211 /* we query the pipe to see if there is any data to read
4212 * to avoid to perform a blocking read */
4213 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4214 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004215 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004216 NULL, /* number of read bytes */
4217 &availableBytes, /* available bytes total */
4218 NULL); /* byteLeft */
4219
4220 repeatCount = 0;
4221 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004222 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004223 {
4224 repeatCount++;
4225 toRead =
4226# ifdef FEAT_MBYTE
4227 (DWORD)(BUFLEN - *buffer_off);
4228# else
4229 (DWORD)BUFLEN;
4230# endif
4231 toRead = availableBytes < toRead ? availableBytes : toRead;
4232 ReadFile(g_hChildStd_OUT_Rd, buffer
4233# ifdef FEAT_MBYTE
4234 + *buffer_off, toRead
4235# else
4236 , toRead
4237# endif
4238 , &len, NULL);
4239
4240 /* If we haven't read anything, there is a problem */
4241 if (len == 0)
4242 break;
4243
4244 availableBytes -= len;
4245
4246 if (options & SHELL_READ)
4247 {
4248 /* Do NUL -> NL translation, append NL separated
4249 * lines to the current buffer. */
4250 for (i = 0; i < len; ++i)
4251 {
4252 if (buffer[i] == NL)
4253 append_ga_line(ga);
4254 else if (buffer[i] == NUL)
4255 ga_append(ga, NL);
4256 else
4257 ga_append(ga, buffer[i]);
4258 }
4259 }
4260# ifdef FEAT_MBYTE
4261 else if (has_mbyte)
4262 {
4263 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004264 int c;
4265 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004266
4267 len += *buffer_off;
4268 buffer[len] = NUL;
4269
4270 /* Check if the last character in buffer[] is
4271 * incomplete, keep these bytes for the next
4272 * round. */
4273 for (p = buffer; p < buffer + len; p += l)
4274 {
4275 l = mb_cptr2len(p);
4276 if (l == 0)
4277 l = 1; /* NUL byte? */
4278 else if (MB_BYTE2LEN(*p) != l)
4279 break;
4280 }
4281 if (p == buffer) /* no complete character */
4282 {
4283 /* avoid getting stuck at an illegal byte */
4284 if (len >= 12)
4285 ++p;
4286 else
4287 {
4288 *buffer_off = len;
4289 return;
4290 }
4291 }
4292 c = *p;
4293 *p = NUL;
4294 msg_puts(buffer);
4295 if (p < buffer + len)
4296 {
4297 *p = c;
4298 *buffer_off = (DWORD)((buffer + len) - p);
4299 mch_memmove(buffer, p, *buffer_off);
4300 return;
4301 }
4302 *buffer_off = 0;
4303 }
4304# endif /* FEAT_MBYTE */
4305 else
4306 {
4307 buffer[len] = NUL;
4308 msg_puts(buffer);
4309 }
4310
4311 windgoto(msg_row, msg_col);
4312 cursor_on();
4313 out_flush();
4314 }
4315}
4316
4317/*
4318 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4319 * for communication and doesn't open any new window.
4320 */
4321 static int
4322mch_system_piped(char *cmd, int options)
4323{
4324 STARTUPINFO si;
4325 PROCESS_INFORMATION pi;
4326 DWORD ret = 0;
4327
4328 HANDLE g_hChildStd_IN_Rd = NULL;
4329 HANDLE g_hChildStd_IN_Wr = NULL;
4330 HANDLE g_hChildStd_OUT_Rd = NULL;
4331 HANDLE g_hChildStd_OUT_Wr = NULL;
4332
4333 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4334 DWORD len;
4335
4336 /* buffer used to receive keys */
4337 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4338 int ta_len = 0; /* valid bytes in ta_buf[] */
4339
4340 DWORD i;
4341 int c;
4342 int noread_cnt = 0;
4343 garray_T ga;
4344 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004345 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004346 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004347
4348 SECURITY_ATTRIBUTES saAttr;
4349
4350 /* Set the bInheritHandle flag so pipe handles are inherited. */
4351 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4352 saAttr.bInheritHandle = TRUE;
4353 saAttr.lpSecurityDescriptor = NULL;
4354
4355 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4356 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4357 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4358 /* Create a pipe for the child process's STDIN. */
4359 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4360 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4361 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4362 {
4363 CloseHandle(g_hChildStd_IN_Rd);
4364 CloseHandle(g_hChildStd_IN_Wr);
4365 CloseHandle(g_hChildStd_OUT_Rd);
4366 CloseHandle(g_hChildStd_OUT_Wr);
4367 MSG_PUTS(_("\nCannot create pipes\n"));
4368 }
4369
4370 si.cb = sizeof(si);
4371 si.lpReserved = NULL;
4372 si.lpDesktop = NULL;
4373 si.lpTitle = NULL;
4374 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4375
4376 /* set-up our file redirection */
4377 si.hStdError = g_hChildStd_OUT_Wr;
4378 si.hStdOutput = g_hChildStd_OUT_Wr;
4379 si.hStdInput = g_hChildStd_IN_Rd;
4380 si.wShowWindow = SW_HIDE;
4381 si.cbReserved2 = 0;
4382 si.lpReserved2 = NULL;
4383
4384 if (options & SHELL_READ)
4385 ga_init2(&ga, 1, BUFLEN);
4386
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004387 if (cmd != NULL)
4388 {
4389 p = (char *)vim_strsave((char_u *)cmd);
4390 if (p != NULL)
4391 unescape_shellxquote((char_u *)p, p_sxe);
4392 else
4393 p = cmd;
4394 }
4395
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004396 /* Now, run the command.
4397 * About "Inherit handles" being TRUE: this command can be litigious,
4398 * handle inheritance was deactivated for pending temp file, but, if we
4399 * deactivate it, the pipes don't work for some reason. */
4400 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004401
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004402 if (p != cmd)
4403 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004404
4405 /* Close our unused side of the pipes */
4406 CloseHandle(g_hChildStd_IN_Rd);
4407 CloseHandle(g_hChildStd_OUT_Wr);
4408
4409 if (options & SHELL_WRITE)
4410 {
4411 HANDLE thread =
4412 CreateThread(NULL, /* security attributes */
4413 0, /* default stack size */
4414 sub_process_writer, /* function to be executed */
4415 g_hChildStd_IN_Wr, /* parameter */
4416 0, /* creation flag, start immediately */
4417 NULL); /* we don't care about thread id */
4418 CloseHandle(thread);
4419 g_hChildStd_IN_Wr = NULL;
4420 }
4421
4422 /* Keep updating the window while waiting for the shell to finish. */
4423 for (;;)
4424 {
4425 MSG msg;
4426
Bram Moolenaar175d0702013-12-11 18:36:33 +01004427 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004428 {
4429 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004430 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004431 }
4432
4433 /* write pipe information in the window */
4434 if ((options & (SHELL_READ|SHELL_WRITE))
4435# ifdef FEAT_GUI
4436 || gui.in_use
4437# endif
4438 )
4439 {
4440 len = 0;
4441 if (!(options & SHELL_EXPAND)
4442 && ((options &
4443 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4444 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4445# ifdef FEAT_GUI
4446 || gui.in_use
4447# endif
4448 )
4449 && (ta_len > 0 || noread_cnt > 4))
4450 {
4451 if (ta_len == 0)
4452 {
4453 /* Get extra characters when we don't have any. Reset the
4454 * counter and timer. */
4455 noread_cnt = 0;
4456# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4457 gettimeofday(&start_tv, NULL);
4458# endif
4459 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4460 }
4461 if (ta_len > 0 || len > 0)
4462 {
4463 /*
4464 * For pipes: Check for CTRL-C: send interrupt signal to
4465 * child. Check for CTRL-D: EOF, close pipe to child.
4466 */
4467 if (len == 1 && cmd != NULL)
4468 {
4469 if (ta_buf[ta_len] == Ctrl_C)
4470 {
4471 /* Learn what exit code is expected, for
4472 * now put 9 as SIGKILL */
4473 TerminateProcess(pi.hProcess, 9);
4474 }
4475 if (ta_buf[ta_len] == Ctrl_D)
4476 {
4477 CloseHandle(g_hChildStd_IN_Wr);
4478 g_hChildStd_IN_Wr = NULL;
4479 }
4480 }
4481
4482 /* replace K_BS by <BS> and K_DEL by <DEL> */
4483 for (i = ta_len; i < ta_len + len; ++i)
4484 {
4485 if (ta_buf[i] == CSI && len - i > 2)
4486 {
4487 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4488 if (c == K_DEL || c == K_KDEL || c == K_BS)
4489 {
4490 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4491 (size_t)(len - i - 2));
4492 if (c == K_DEL || c == K_KDEL)
4493 ta_buf[i] = DEL;
4494 else
4495 ta_buf[i] = Ctrl_H;
4496 len -= 2;
4497 }
4498 }
4499 else if (ta_buf[i] == '\r')
4500 ta_buf[i] = '\n';
4501# ifdef FEAT_MBYTE
4502 if (has_mbyte)
4503 i += (*mb_ptr2len_len)(ta_buf + i,
4504 ta_len + len - i) - 1;
4505# endif
4506 }
4507
4508 /*
4509 * For pipes: echo the typed characters. For a pty this
4510 * does not seem to work.
4511 */
4512 for (i = ta_len; i < ta_len + len; ++i)
4513 {
4514 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4515 msg_putchar(ta_buf[i]);
4516# ifdef FEAT_MBYTE
4517 else if (has_mbyte)
4518 {
4519 int l = (*mb_ptr2len)(ta_buf + i);
4520
4521 msg_outtrans_len(ta_buf + i, l);
4522 i += l - 1;
4523 }
4524# endif
4525 else
4526 msg_outtrans_len(ta_buf + i, 1);
4527 }
4528 windgoto(msg_row, msg_col);
4529 out_flush();
4530
4531 ta_len += len;
4532
4533 /*
4534 * Write the characters to the child, unless EOF has been
4535 * typed for pipes. Write one character at a time, to
4536 * avoid losing too much typeahead. When writing buffer
4537 * lines, drop the typed characters (only check for
4538 * CTRL-C).
4539 */
4540 if (options & SHELL_WRITE)
4541 ta_len = 0;
4542 else if (g_hChildStd_IN_Wr != NULL)
4543 {
4544 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4545 1, &len, NULL);
4546 // if we are typing in, we want to keep things reactive
4547 delay = 1;
4548 if (len > 0)
4549 {
4550 ta_len -= len;
4551 mch_memmove(ta_buf, ta_buf + len, ta_len);
4552 }
4553 }
4554 }
4555 }
4556 }
4557
4558 if (ta_len)
4559 ui_inchar_undo(ta_buf, ta_len);
4560
4561 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4562 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004563 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004564 break;
4565 }
4566
4567 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004568 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004569
4570 /* We start waiting for a very short time and then increase it, so
4571 * that we respond quickly when the process is quick, and don't
4572 * consume too much overhead when it's slow. */
4573 if (delay < 50)
4574 delay += 10;
4575 }
4576
4577 /* Close the pipe */
4578 CloseHandle(g_hChildStd_OUT_Rd);
4579 if (g_hChildStd_IN_Wr != NULL)
4580 CloseHandle(g_hChildStd_IN_Wr);
4581
4582 WaitForSingleObject(pi.hProcess, INFINITE);
4583
4584 /* Get the command exit code */
4585 GetExitCodeProcess(pi.hProcess, &ret);
4586
4587 if (options & SHELL_READ)
4588 {
4589 if (ga.ga_len > 0)
4590 {
4591 append_ga_line(&ga);
4592 /* remember that the NL was missing */
4593 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4594 }
4595 else
4596 curbuf->b_no_eol_lnum = 0;
4597 ga_clear(&ga);
4598 }
4599
4600 /* Close the handles to the subprocess, so that it goes away */
4601 CloseHandle(pi.hThread);
4602 CloseHandle(pi.hProcess);
4603
4604 return ret;
4605}
4606
4607 static int
4608mch_system(char *cmd, int options)
4609{
4610 /* if we can pipe and the shelltemp option is off */
4611 if (allowPiping && !p_stmp)
4612 return mch_system_piped(cmd, options);
4613 else
4614 return mch_system_classic(cmd, options);
4615}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004616#else
4617
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004618# ifdef FEAT_MBYTE
4619 static int
4620mch_system(char *cmd, int options)
4621{
4622 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4623 {
4624 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4625 if (wcmd != NULL)
4626 {
4627 int ret = _wsystem(wcmd);
4628 vim_free(wcmd);
4629 return ret;
4630 }
4631 }
4632 return system(cmd);
4633}
4634# else
4635# define mch_system(c, o) system(c)
4636# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004637
4638#endif
4639
4640/*
4641 * Either execute a command by calling the shell or start a new shell
4642 */
4643 int
4644mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004645 char_u *cmd,
4646 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004647{
4648 int x = 0;
4649 int tmode = cur_tmode;
4650#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004651 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004652# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004653 int did_set_title = FALSE;
4654
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004655 /* Change the title to reflect that we are in a subshell. */
4656 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4657 {
4658 WCHAR szShellTitle[512];
4659
4660 if (GetConsoleTitleW(szShellTitle,
4661 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4662 {
4663 if (cmd == NULL)
4664 wcscat(szShellTitle, L" :sh");
4665 else
4666 {
4667 WCHAR *wn = enc_to_utf16(cmd, NULL);
4668
4669 if (wn != NULL)
4670 {
4671 wcscat(szShellTitle, L" - !");
4672 if ((wcslen(szShellTitle) + wcslen(wn) <
4673 sizeof(szShellTitle)/sizeof(WCHAR)))
4674 wcscat(szShellTitle, wn);
4675 SetConsoleTitleW(szShellTitle);
4676 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004677 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004678 }
4679 }
4680 }
4681 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004682 if (!did_set_title)
4683# endif
4684 /* Change the title to reflect that we are in a subshell. */
4685 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004686 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004687 if (cmd == NULL)
4688 strcat(szShellTitle, " :sh");
4689 else
4690 {
4691 strcat(szShellTitle, " - !");
4692 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4693 strcat(szShellTitle, cmd);
4694 }
4695 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004696 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004697#endif
4698
4699 out_flush();
4700
4701#ifdef MCH_WRITE_DUMP
4702 if (fdDump)
4703 {
4704 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4705 fflush(fdDump);
4706 }
4707#endif
4708
4709 /*
4710 * Catch all deadly signals while running the external command, because a
4711 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4712 */
4713 signal(SIGINT, SIG_IGN);
4714#if defined(__GNUC__) && !defined(__MINGW32__)
4715 signal(SIGKILL, SIG_IGN);
4716#else
4717 signal(SIGBREAK, SIG_IGN);
4718#endif
4719 signal(SIGILL, SIG_IGN);
4720 signal(SIGFPE, SIG_IGN);
4721 signal(SIGSEGV, SIG_IGN);
4722 signal(SIGTERM, SIG_IGN);
4723 signal(SIGABRT, SIG_IGN);
4724
4725 if (options & SHELL_COOKED)
4726 settmode(TMODE_COOK); /* set to normal mode */
4727
4728 if (cmd == NULL)
4729 {
4730 x = mch_system(p_sh, options);
4731 }
4732 else
4733 {
4734 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004735 char_u *newcmd = NULL;
4736 char_u *cmdbase = cmd;
4737 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004738
4739 /* Skip a leading ", ( and "(. */
4740 if (*cmdbase == '"' )
4741 ++cmdbase;
4742 if (*cmdbase == '(')
4743 ++cmdbase;
4744
4745 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4746 {
4747 STARTUPINFO si;
4748 PROCESS_INFORMATION pi;
4749 DWORD flags = CREATE_NEW_CONSOLE;
4750 char_u *p;
4751
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004752 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004753 si.cb = sizeof(si);
4754 si.lpReserved = NULL;
4755 si.lpDesktop = NULL;
4756 si.lpTitle = NULL;
4757 si.dwFlags = 0;
4758 si.cbReserved2 = 0;
4759 si.lpReserved2 = NULL;
4760
4761 cmdbase = skipwhite(cmdbase + 5);
4762 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4763 && vim_iswhite(cmdbase[4]))
4764 {
4765 cmdbase = skipwhite(cmdbase + 4);
4766 si.dwFlags = STARTF_USESHOWWINDOW;
4767 si.wShowWindow = SW_SHOWMINNOACTIVE;
4768 }
4769 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4770 && vim_iswhite(cmdbase[2]))
4771 {
4772 cmdbase = skipwhite(cmdbase + 2);
4773 flags = CREATE_NO_WINDOW;
4774 si.dwFlags = STARTF_USESTDHANDLES;
4775 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004776 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004777 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004778 NULL, // Security att.
4779 OPEN_EXISTING, // Open flags
4780 FILE_ATTRIBUTE_NORMAL, // File att.
4781 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004782 si.hStdOutput = si.hStdInput;
4783 si.hStdError = si.hStdInput;
4784 }
4785
4786 /* Remove a trailing ", ) and )" if they have a match
4787 * at the start of the command. */
4788 if (cmdbase > cmd)
4789 {
4790 p = cmdbase + STRLEN(cmdbase);
4791 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4792 *--p = NUL;
4793 if (p > cmdbase && p[-1] == ')'
4794 && (*cmd =='(' || cmd[1] == '('))
4795 *--p = NUL;
4796 }
4797
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004798 newcmd = cmdbase;
4799 unescape_shellxquote(cmdbase, p_sxe);
4800
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004801 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004802 * If creating new console, arguments are passed to the
4803 * 'cmd.exe' as-is. If it's not, arguments are not treated
4804 * correctly for current 'cmd.exe'. So unescape characters in
4805 * shellxescape except '|' for avoiding to be treated as
4806 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004807 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004808 if (flags != CREATE_NEW_CONSOLE)
4809 {
4810 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004811 char_u *cmd_shell = mch_getenv("COMSPEC");
4812
4813 if (cmd_shell == NULL || *cmd_shell == NUL)
4814 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004815
4816 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4817 if (subcmd != NULL)
4818 {
4819 /* make "cmd.exe /c arguments" */
4820 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004821 newcmd = lalloc(cmdlen, TRUE);
4822 if (newcmd != NULL)
4823 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004824 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004825 else
4826 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004827 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004828 }
4829 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004830
4831 /*
4832 * Now, start the command as a process, so that it doesn't
4833 * inherit our handles which causes unpleasant dangling swap
4834 * files if we exit before the spawned process
4835 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004836 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004837 x = 0;
4838 else
4839 {
4840 x = -1;
4841#ifdef FEAT_GUI_W32
4842 EMSG(_("E371: Command not found"));
4843#endif
4844 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004845
4846 if (newcmd != cmdbase)
4847 vim_free(newcmd);
4848
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004849 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004850 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004851 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004852 CloseHandle(si.hStdInput);
4853 }
4854 /* Close the handles to the subprocess, so that it goes away */
4855 CloseHandle(pi.hThread);
4856 CloseHandle(pi.hProcess);
4857 }
4858 else
4859 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004860 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004861#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004862 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004863#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004864 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4865
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004866 newcmd = lalloc(cmdlen, TRUE);
4867 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004868 {
4869#if defined(FEAT_GUI_W32)
4870 if (need_vimrun_warning)
4871 {
4872 MessageBox(NULL,
4873 _("VIMRUN.EXE not found in your $PATH.\n"
4874 "External commands will not pause after completion.\n"
4875 "See :help win32-vimrun for more information."),
4876 _("Vim Warning"),
4877 MB_ICONWARNING);
4878 need_vimrun_warning = FALSE;
4879 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004880 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004881 /* Use vimrun to execute the command. It opens a console
4882 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004883 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004884 vimrun_path,
4885 (msg_silent != 0 || (options & SHELL_DOOUT))
4886 ? "-s " : "",
4887 p_sh, p_shcf, cmd);
4888 else
4889#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004890 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004891 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004892 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004893 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004894 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004895 }
4896 }
4897
4898 if (tmode == TMODE_RAW)
4899 settmode(TMODE_RAW); /* set to raw mode */
4900
4901 /* Print the return value, unless "vimrun" was used. */
4902 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4903#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004904 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4905 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004906#endif
4907 )
4908 {
4909 smsg(_("shell returned %d"), x);
4910 msg_putchar('\n');
4911 }
4912#ifdef FEAT_TITLE
4913 resettitle();
4914#endif
4915
4916 signal(SIGINT, SIG_DFL);
4917#if defined(__GNUC__) && !defined(__MINGW32__)
4918 signal(SIGKILL, SIG_DFL);
4919#else
4920 signal(SIGBREAK, SIG_DFL);
4921#endif
4922 signal(SIGILL, SIG_DFL);
4923 signal(SIGFPE, SIG_DFL);
4924 signal(SIGSEGV, SIG_DFL);
4925 signal(SIGTERM, SIG_DFL);
4926 signal(SIGABRT, SIG_DFL);
4927
4928 return x;
4929}
4930
4931
4932#ifndef FEAT_GUI_W32
4933
4934/*
4935 * Start termcap mode
4936 */
4937 static void
4938termcap_mode_start(void)
4939{
4940 DWORD cmodein;
4941
4942 if (g_fTermcapMode)
4943 return;
4944
4945 SaveConsoleBuffer(&g_cbNonTermcap);
4946
4947 if (g_cbTermcap.IsValid)
4948 {
4949 /*
4950 * We've been in termcap mode before. Restore certain screen
4951 * characteristics, including the buffer size and the window
4952 * size. Since we will be redrawing the screen, we don't need
4953 * to restore the actual contents of the buffer.
4954 */
4955 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4956 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4957 Rows = g_cbTermcap.Info.dwSize.Y;
4958 Columns = g_cbTermcap.Info.dwSize.X;
4959 }
4960 else
4961 {
4962 /*
4963 * This is our first time entering termcap mode. Clear the console
4964 * screen buffer, and resize the buffer to match the current window
4965 * size. We will use this as the size of our editing environment.
4966 */
4967 ClearConsoleBuffer(g_attrCurrent);
4968 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4969 }
4970
4971#ifdef FEAT_TITLE
4972 resettitle();
4973#endif
4974
4975 GetConsoleMode(g_hConIn, &cmodein);
4976#ifdef FEAT_MOUSE
4977 if (g_fMouseActive)
4978 cmodein |= ENABLE_MOUSE_INPUT;
4979 else
4980 cmodein &= ~ENABLE_MOUSE_INPUT;
4981#endif
4982 cmodein |= ENABLE_WINDOW_INPUT;
4983 SetConsoleMode(g_hConIn, cmodein);
4984
4985 redraw_later_clear();
4986 g_fTermcapMode = TRUE;
4987}
4988
4989
4990/*
4991 * End termcap mode
4992 */
4993 static void
4994termcap_mode_end(void)
4995{
4996 DWORD cmodein;
4997 ConsoleBuffer *cb;
4998 COORD coord;
4999 DWORD dwDummy;
5000
5001 if (!g_fTermcapMode)
5002 return;
5003
5004 SaveConsoleBuffer(&g_cbTermcap);
5005
5006 GetConsoleMode(g_hConIn, &cmodein);
5007 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5008 SetConsoleMode(g_hConIn, cmodein);
5009
5010#ifdef FEAT_RESTORE_ORIG_SCREEN
5011 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5012#else
5013 cb = &g_cbNonTermcap;
5014#endif
5015 RestoreConsoleBuffer(cb, p_rs);
5016 SetConsoleCursorInfo(g_hConOut, &g_cci);
5017
5018 if (p_rs || exiting)
5019 {
5020 /*
5021 * Clear anything that happens to be on the current line.
5022 */
5023 coord.X = 0;
5024 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5025 FillConsoleOutputCharacter(g_hConOut, ' ',
5026 cb->Info.dwSize.X, coord, &dwDummy);
5027 /*
5028 * The following is just for aesthetics. If we are exiting without
5029 * restoring the screen, then we want to have a prompt string
5030 * appear at the bottom line. However, the command interpreter
5031 * seems to always advance the cursor one line before displaying
5032 * the prompt string, which causes the screen to scroll. To
5033 * counter this, move the cursor up one line before exiting.
5034 */
5035 if (exiting && !p_rs)
5036 coord.Y--;
5037 /*
5038 * Position the cursor at the leftmost column of the desired row.
5039 */
5040 SetConsoleCursorPosition(g_hConOut, coord);
5041 }
5042
5043 g_fTermcapMode = FALSE;
5044}
5045#endif /* FEAT_GUI_W32 */
5046
5047
5048#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005049/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005050 void
5051mch_write(
5052 char_u *s,
5053 int len)
5054{
5055 /* never used */
5056}
5057
5058#else
5059
5060/*
5061 * clear `n' chars, starting from `coord'
5062 */
5063 static void
5064clear_chars(
5065 COORD coord,
5066 DWORD n)
5067{
5068 DWORD dwDummy;
5069
5070 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5071 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5072}
5073
5074
5075/*
5076 * Clear the screen
5077 */
5078 static void
5079clear_screen(void)
5080{
5081 g_coord.X = g_coord.Y = 0;
5082 clear_chars(g_coord, Rows * Columns);
5083}
5084
5085
5086/*
5087 * Clear to end of display
5088 */
5089 static void
5090clear_to_end_of_display(void)
5091{
5092 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5093 * Columns + (Columns - g_coord.X));
5094}
5095
5096
5097/*
5098 * Clear to end of line
5099 */
5100 static void
5101clear_to_end_of_line(void)
5102{
5103 clear_chars(g_coord, Columns - g_coord.X);
5104}
5105
5106
5107/*
5108 * Scroll the scroll region up by `cLines' lines
5109 */
5110 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005111scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005112{
5113 COORD oldcoord = g_coord;
5114
5115 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5116 delete_lines(cLines);
5117
5118 g_coord = oldcoord;
5119}
5120
5121
5122/*
5123 * Set the scroll region
5124 */
5125 static void
5126set_scroll_region(
5127 unsigned left,
5128 unsigned top,
5129 unsigned right,
5130 unsigned bottom)
5131{
5132 if (left >= right
5133 || top >= bottom
5134 || right > (unsigned) Columns - 1
5135 || bottom > (unsigned) Rows - 1)
5136 return;
5137
5138 g_srScrollRegion.Left = left;
5139 g_srScrollRegion.Top = top;
5140 g_srScrollRegion.Right = right;
5141 g_srScrollRegion.Bottom = bottom;
5142}
5143
5144
5145/*
5146 * Insert `cLines' lines at the current cursor position
5147 */
5148 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005149insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005150{
5151 SMALL_RECT source;
5152 COORD dest;
5153 CHAR_INFO fill;
5154
5155 dest.X = 0;
5156 dest.Y = g_coord.Y + cLines;
5157
5158 source.Left = 0;
5159 source.Top = g_coord.Y;
5160 source.Right = g_srScrollRegion.Right;
5161 source.Bottom = g_srScrollRegion.Bottom - cLines;
5162
5163 fill.Char.AsciiChar = ' ';
5164 fill.Attributes = g_attrCurrent;
5165
5166 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5167
5168 /* Here we have to deal with a win32 console flake: If the scroll
5169 * region looks like abc and we scroll c to a and fill with d we get
5170 * cbd... if we scroll block c one line at a time to a, we get cdd...
5171 * vim expects cdd consistently... So we have to deal with that
5172 * here... (this also occurs scrolling the same way in the other
5173 * direction). */
5174
5175 if (source.Bottom < dest.Y)
5176 {
5177 COORD coord;
5178
5179 coord.X = 0;
5180 coord.Y = source.Bottom;
5181 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5182 }
5183}
5184
5185
5186/*
5187 * Delete `cLines' lines at the current cursor position
5188 */
5189 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005190delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191{
5192 SMALL_RECT source;
5193 COORD dest;
5194 CHAR_INFO fill;
5195 int nb;
5196
5197 dest.X = 0;
5198 dest.Y = g_coord.Y;
5199
5200 source.Left = 0;
5201 source.Top = g_coord.Y + cLines;
5202 source.Right = g_srScrollRegion.Right;
5203 source.Bottom = g_srScrollRegion.Bottom;
5204
5205 fill.Char.AsciiChar = ' ';
5206 fill.Attributes = g_attrCurrent;
5207
5208 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5209
5210 /* Here we have to deal with a win32 console flake: If the scroll
5211 * region looks like abc and we scroll c to a and fill with d we get
5212 * cbd... if we scroll block c one line at a time to a, we get cdd...
5213 * vim expects cdd consistently... So we have to deal with that
5214 * here... (this also occurs scrolling the same way in the other
5215 * direction). */
5216
5217 nb = dest.Y + (source.Bottom - source.Top) + 1;
5218
5219 if (nb < source.Top)
5220 {
5221 COORD coord;
5222
5223 coord.X = 0;
5224 coord.Y = nb;
5225 clear_chars(coord, Columns * (source.Top - nb));
5226 }
5227}
5228
5229
5230/*
5231 * Set the cursor position
5232 */
5233 static void
5234gotoxy(
5235 unsigned x,
5236 unsigned y)
5237{
5238 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5239 return;
5240
5241 /* external cursor coords are 1-based; internal are 0-based */
5242 g_coord.X = x - 1;
5243 g_coord.Y = y - 1;
5244 SetConsoleCursorPosition(g_hConOut, g_coord);
5245}
5246
5247
5248/*
5249 * Set the current text attribute = (foreground | background)
5250 * See ../doc/os_win32.txt for the numbers.
5251 */
5252 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005253textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005254{
5255 g_attrCurrent = wAttr;
5256
5257 SetConsoleTextAttribute(g_hConOut, wAttr);
5258}
5259
5260
5261 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005262textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005263{
5264 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
5265
5266 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5267}
5268
5269
5270 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005271textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005272{
5273 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
5274
5275 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5276}
5277
5278
5279/*
5280 * restore the default text attribute (whatever we started with)
5281 */
5282 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005283normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005284{
5285 textattr(g_attrDefault);
5286}
5287
5288
5289static WORD g_attrPreStandout = 0;
5290
5291/*
5292 * Make the text standout, by brightening it
5293 */
5294 static void
5295standout(void)
5296{
5297 g_attrPreStandout = g_attrCurrent;
5298 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5299}
5300
5301
5302/*
5303 * Turn off standout mode
5304 */
5305 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005306standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005307{
5308 if (g_attrPreStandout)
5309 {
5310 textattr(g_attrPreStandout);
5311 g_attrPreStandout = 0;
5312 }
5313}
5314
5315
5316/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005317 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005318 */
5319 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005320mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005321{
5322 char_u *p;
5323 int n;
5324
5325 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5326 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5327 if (T_ME[0] == ESC && T_ME[1] == '|')
5328 {
5329 p = T_ME + 2;
5330 n = getdigits(&p);
5331 if (*p == 'm' && n > 0)
5332 {
5333 cterm_normal_fg_color = (n & 0xf) + 1;
5334 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5335 }
5336 }
5337}
5338
5339
5340/*
5341 * visual bell: flash the screen
5342 */
5343 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005344visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005345{
5346 COORD coordOrigin = {0, 0};
5347 WORD attrFlash = ~g_attrCurrent & 0xff;
5348
5349 DWORD dwDummy;
5350 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5351
5352 if (oldattrs == NULL)
5353 return;
5354 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5355 coordOrigin, &dwDummy);
5356 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5357 coordOrigin, &dwDummy);
5358
5359 Sleep(15); /* wait for 15 msec */
5360 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5361 coordOrigin, &dwDummy);
5362 vim_free(oldattrs);
5363}
5364
5365
5366/*
5367 * Make the cursor visible or invisible
5368 */
5369 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005370cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005371{
5372 s_cursor_visible = fVisible;
5373#ifdef MCH_CURSOR_SHAPE
5374 mch_update_cursor();
5375#endif
5376}
5377
5378
5379/*
5380 * write `cchToWrite' characters in `pchBuf' to the screen
5381 * Returns the number of characters actually written (at least one).
5382 */
5383 static BOOL
5384write_chars(
5385 LPCSTR pchBuf,
5386 DWORD cchToWrite)
5387{
5388 COORD coord = g_coord;
5389 DWORD written;
5390
5391 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
5392 coord, &written);
5393 /* When writing fails or didn't write a single character, pretend one
5394 * character was written, otherwise we get stuck. */
5395 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
5396 coord, &written) == 0
5397 || written == 0)
5398 written = 1;
5399
5400 g_coord.X += (SHORT) written;
5401
5402 while (g_coord.X > g_srScrollRegion.Right)
5403 {
5404 g_coord.X -= (SHORT) Columns;
5405 if (g_coord.Y < g_srScrollRegion.Bottom)
5406 g_coord.Y++;
5407 }
5408
5409 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5410
5411 return written;
5412}
5413
5414
5415/*
5416 * mch_write(): write the output buffer to the screen, translating ESC
5417 * sequences into calls to console output routines.
5418 */
5419 void
5420mch_write(
5421 char_u *s,
5422 int len)
5423{
5424 s[len] = NUL;
5425
5426 if (!term_console)
5427 {
5428 write(1, s, (unsigned)len);
5429 return;
5430 }
5431
5432 /* translate ESC | sequences into faked bios calls */
5433 while (len--)
5434 {
5435 /* optimization: use one single write_chars for runs of text,
5436 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005437 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005438
5439 if (p_wd)
5440 {
5441 WaitForChar(p_wd);
5442 if (prefix != 0)
5443 prefix = 1;
5444 }
5445
5446 if (prefix != 0)
5447 {
5448 DWORD nWritten;
5449
5450 nWritten = write_chars(s, prefix);
5451#ifdef MCH_WRITE_DUMP
5452 if (fdDump)
5453 {
5454 fputc('>', fdDump);
5455 fwrite(s, sizeof(char_u), nWritten, fdDump);
5456 fputs("<\n", fdDump);
5457 }
5458#endif
5459 len -= (nWritten - 1);
5460 s += nWritten;
5461 }
5462 else if (s[0] == '\n')
5463 {
5464 /* \n, newline: go to the beginning of the next line or scroll */
5465 if (g_coord.Y == g_srScrollRegion.Bottom)
5466 {
5467 scroll(1);
5468 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5469 }
5470 else
5471 {
5472 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5473 }
5474#ifdef MCH_WRITE_DUMP
5475 if (fdDump)
5476 fputs("\\n\n", fdDump);
5477#endif
5478 s++;
5479 }
5480 else if (s[0] == '\r')
5481 {
5482 /* \r, carriage return: go to beginning of line */
5483 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5484#ifdef MCH_WRITE_DUMP
5485 if (fdDump)
5486 fputs("\\r\n", fdDump);
5487#endif
5488 s++;
5489 }
5490 else if (s[0] == '\b')
5491 {
5492 /* \b, backspace: move cursor one position left */
5493 if (g_coord.X > g_srScrollRegion.Left)
5494 g_coord.X--;
5495 else if (g_coord.Y > g_srScrollRegion.Top)
5496 {
5497 g_coord.X = g_srScrollRegion.Right;
5498 g_coord.Y--;
5499 }
5500 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5501#ifdef MCH_WRITE_DUMP
5502 if (fdDump)
5503 fputs("\\b\n", fdDump);
5504#endif
5505 s++;
5506 }
5507 else if (s[0] == '\a')
5508 {
5509 /* \a, bell */
5510 MessageBeep(0xFFFFFFFF);
5511#ifdef MCH_WRITE_DUMP
5512 if (fdDump)
5513 fputs("\\a\n", fdDump);
5514#endif
5515 s++;
5516 }
5517 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5518 {
5519#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005520 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005521#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005522 char_u *p;
5523 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005524
5525 switch (s[2])
5526 {
5527 /* one or two numeric arguments, separated by ';' */
5528
5529 case '0': case '1': case '2': case '3': case '4':
5530 case '5': case '6': case '7': case '8': case '9':
5531 p = s + 2;
5532 arg1 = getdigits(&p); /* no check for length! */
5533 if (p > s + len)
5534 break;
5535
5536 if (*p == ';')
5537 {
5538 ++p;
5539 arg2 = getdigits(&p); /* no check for length! */
5540 if (p > s + len)
5541 break;
5542
5543 if (*p == 'H')
5544 gotoxy(arg2, arg1);
5545 else if (*p == 'r')
5546 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5547 }
5548 else if (*p == 'A')
5549 {
5550 /* move cursor up arg1 lines in same column */
5551 gotoxy(g_coord.X + 1,
5552 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5553 }
5554 else if (*p == 'C')
5555 {
5556 /* move cursor right arg1 columns in same line */
5557 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5558 g_coord.Y + 1);
5559 }
5560 else if (*p == 'H')
5561 {
5562 gotoxy(1, arg1);
5563 }
5564 else if (*p == 'L')
5565 {
5566 insert_lines(arg1);
5567 }
5568 else if (*p == 'm')
5569 {
5570 if (arg1 == 0)
5571 normvideo();
5572 else
5573 textattr((WORD) arg1);
5574 }
5575 else if (*p == 'f')
5576 {
5577 textcolor((WORD) arg1);
5578 }
5579 else if (*p == 'b')
5580 {
5581 textbackground((WORD) arg1);
5582 }
5583 else if (*p == 'M')
5584 {
5585 delete_lines(arg1);
5586 }
5587
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005588 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589 s = p + 1;
5590 break;
5591
5592
5593 /* Three-character escape sequences */
5594
5595 case 'A':
5596 /* move cursor up one line in same column */
5597 gotoxy(g_coord.X + 1,
5598 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5599 goto got3;
5600
5601 case 'B':
5602 visual_bell();
5603 goto got3;
5604
5605 case 'C':
5606 /* move cursor right one column in same line */
5607 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5608 g_coord.Y + 1);
5609 goto got3;
5610
5611 case 'E':
5612 termcap_mode_end();
5613 goto got3;
5614
5615 case 'F':
5616 standout();
5617 goto got3;
5618
5619 case 'f':
5620 standend();
5621 goto got3;
5622
5623 case 'H':
5624 gotoxy(1, 1);
5625 goto got3;
5626
5627 case 'j':
5628 clear_to_end_of_display();
5629 goto got3;
5630
5631 case 'J':
5632 clear_screen();
5633 goto got3;
5634
5635 case 'K':
5636 clear_to_end_of_line();
5637 goto got3;
5638
5639 case 'L':
5640 insert_lines(1);
5641 goto got3;
5642
5643 case 'M':
5644 delete_lines(1);
5645 goto got3;
5646
5647 case 'S':
5648 termcap_mode_start();
5649 goto got3;
5650
5651 case 'V':
5652 cursor_visible(TRUE);
5653 goto got3;
5654
5655 case 'v':
5656 cursor_visible(FALSE);
5657 goto got3;
5658
5659 got3:
5660 s += 3;
5661 len -= 2;
5662 }
5663
5664#ifdef MCH_WRITE_DUMP
5665 if (fdDump)
5666 {
5667 fputs("ESC | ", fdDump);
5668 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5669 fputc('\n', fdDump);
5670 }
5671#endif
5672 }
5673 else
5674 {
5675 /* Write a single character */
5676 DWORD nWritten;
5677
5678 nWritten = write_chars(s, 1);
5679#ifdef MCH_WRITE_DUMP
5680 if (fdDump)
5681 {
5682 fputc('>', fdDump);
5683 fwrite(s, sizeof(char_u), nWritten, fdDump);
5684 fputs("<\n", fdDump);
5685 }
5686#endif
5687
5688 len -= (nWritten - 1);
5689 s += nWritten;
5690 }
5691 }
5692
5693#ifdef MCH_WRITE_DUMP
5694 if (fdDump)
5695 fflush(fdDump);
5696#endif
5697}
5698
5699#endif /* FEAT_GUI_W32 */
5700
5701
5702/*
5703 * Delay for half a second.
5704 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005705/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005706 void
5707mch_delay(
5708 long msec,
5709 int ignoreinput)
5710{
5711#ifdef FEAT_GUI_W32
5712 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005713#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005715# ifdef FEAT_MZSCHEME
5716 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5717 {
5718 int towait = p_mzq;
5719
5720 /* if msec is large enough, wait by portions in p_mzq */
5721 while (msec > 0)
5722 {
5723 mzvim_check_threads();
5724 if (msec < towait)
5725 towait = msec;
5726 Sleep(towait);
5727 msec -= towait;
5728 }
5729 }
5730 else
5731# endif
5732 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005733 else
5734 WaitForChar(msec);
5735#endif
5736}
5737
5738
5739/*
5740 * this version of remove is not scared by a readonly (backup) file
5741 * Return 0 for success, -1 for failure.
5742 */
5743 int
5744mch_remove(char_u *name)
5745{
5746#ifdef FEAT_MBYTE
5747 WCHAR *wn = NULL;
5748 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005749#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005750
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005751 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5752
5753#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005754 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5755 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005756 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005757 if (wn != NULL)
5758 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005759 n = DeleteFileW(wn) ? 0 : -1;
5760 vim_free(wn);
5761 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5762 return n;
5763 /* Retry with non-wide function (for Windows 98). */
5764 }
5765 }
5766#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005767 return DeleteFile(name) ? 0 : -1;
5768}
5769
5770
5771/*
5772 * check for an "interrupt signal": CTRL-break or CTRL-C
5773 */
5774 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005775mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776{
5777#ifndef FEAT_GUI_W32 /* never used */
5778 if (g_fCtrlCPressed || g_fCBrkPressed)
5779 {
5780 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5781 got_int = TRUE;
5782 }
5783#endif
5784}
5785
5786
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787#ifdef FEAT_MBYTE
5788/*
5789 * Same code as below, but with wide functions and no comments.
5790 * Return 0 for success, non-zero for failure.
5791 */
5792 int
5793mch_wrename(WCHAR *wold, WCHAR *wnew)
5794{
5795 WCHAR *p;
5796 int i;
5797 WCHAR szTempFile[_MAX_PATH + 1];
5798 WCHAR szNewPath[_MAX_PATH + 1];
5799 HANDLE hf;
5800
5801 if (!mch_windows95())
5802 {
5803 p = wold;
5804 for (i = 0; wold[i] != NUL; ++i)
5805 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5806 && wold[i + 1] != 0)
5807 p = wold + i + 1;
5808 if ((int)(wold + i - p) < 8 || p[6] != '~')
5809 return (MoveFileW(wold, wnew) == 0);
5810 }
5811
5812 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5813 return -1;
5814 *p = NUL;
5815
5816 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5817 return -2;
5818
5819 if (!DeleteFileW(szTempFile))
5820 return -3;
5821
5822 if (!MoveFileW(wold, szTempFile))
5823 return -4;
5824
5825 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5826 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5827 return -5;
5828 if (!CloseHandle(hf))
5829 return -6;
5830
5831 if (!MoveFileW(szTempFile, wnew))
5832 {
5833 (void)MoveFileW(szTempFile, wold);
5834 return -7;
5835 }
5836
5837 DeleteFileW(szTempFile);
5838
5839 if (!DeleteFileW(wold))
5840 return -8;
5841
5842 return 0;
5843}
5844#endif
5845
5846
5847/*
5848 * mch_rename() works around a bug in rename (aka MoveFile) in
5849 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5850 * file whose short file name is "FOO.BAR" (its long file name will
5851 * be correct: "foo.bar~"). Because a file can be accessed by
5852 * either its SFN or its LFN, "foo.bar" has effectively been
5853 * renamed to "foo.bar", which is not at all what was wanted. This
5854 * seems to happen only when renaming files with three-character
5855 * extensions by appending a suffix that does not include ".".
5856 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5857 *
5858 * There is another problem, which isn't really a bug but isn't right either:
5859 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5860 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5861 * service pack 6. Doesn't seem to happen on Windows 98.
5862 *
5863 * Like rename(), returns 0 upon success, non-zero upon failure.
5864 * Should probably set errno appropriately when errors occur.
5865 */
5866 int
5867mch_rename(
5868 const char *pszOldFile,
5869 const char *pszNewFile)
5870{
5871 char szTempFile[_MAX_PATH+1];
5872 char szNewPath[_MAX_PATH+1];
5873 char *pszFilePart;
5874 HANDLE hf;
5875#ifdef FEAT_MBYTE
5876 WCHAR *wold = NULL;
5877 WCHAR *wnew = NULL;
5878 int retval = -1;
5879
5880 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5881 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005882 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5883 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005884 if (wold != NULL && wnew != NULL)
5885 retval = mch_wrename(wold, wnew);
5886 vim_free(wold);
5887 vim_free(wnew);
5888 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5889 return retval;
5890 /* Retry with non-wide function (for Windows 98). */
5891 }
5892#endif
5893
5894 /*
5895 * No need to play tricks if not running Windows 95, unless the file name
5896 * contains a "~" as the seventh character.
5897 */
5898 if (!mch_windows95())
5899 {
5900 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5901 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5902 return rename(pszOldFile, pszNewFile);
5903 }
5904
5905 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5906 * a directory, no error is returned and pszFilePart will be NULL. */
5907 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5908 || pszFilePart == NULL)
5909 return -1;
5910 *pszFilePart = NUL;
5911
5912 /* Get (and create) a unique temporary file name in directory of new file */
5913 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5914 return -2;
5915
5916 /* blow the temp file away */
5917 if (!DeleteFile(szTempFile))
5918 return -3;
5919
5920 /* rename old file to the temp file */
5921 if (!MoveFile(pszOldFile, szTempFile))
5922 return -4;
5923
5924 /* now create an empty file called pszOldFile; this prevents the operating
5925 * system using pszOldFile as an alias (SFN) if we're renaming within the
5926 * same directory. For example, we're editing a file called
5927 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5928 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5929 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005930 * cause all sorts of problems later in buf_write(). So, we create an
5931 * empty file called filena~1.txt and the system will have to find some
5932 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005933 */
5934 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5935 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5936 return -5;
5937 if (!CloseHandle(hf))
5938 return -6;
5939
5940 /* rename the temp file to the new file */
5941 if (!MoveFile(szTempFile, pszNewFile))
5942 {
5943 /* Renaming failed. Rename the file back to its old name, so that it
5944 * looks like nothing happened. */
5945 (void)MoveFile(szTempFile, pszOldFile);
5946
5947 return -7;
5948 }
5949
5950 /* Seems to be left around on Novell filesystems */
5951 DeleteFile(szTempFile);
5952
5953 /* finally, remove the empty old file */
5954 if (!DeleteFile(pszOldFile))
5955 return -8;
5956
5957 return 0; /* success */
5958}
5959
5960/*
5961 * Get the default shell for the current hardware platform
5962 */
5963 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005964default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005965{
5966 char* psz = NULL;
5967
5968 PlatformId();
5969
5970 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5971 psz = "cmd.exe";
5972 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5973 psz = "command.com";
5974
5975 return psz;
5976}
5977
5978/*
5979 * mch_access() extends access() to do more detailed check on network drives.
5980 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5981 */
5982 int
5983mch_access(char *n, int p)
5984{
5985 HANDLE hFile;
5986 DWORD am;
5987 int retval = -1; /* default: fail */
5988#ifdef FEAT_MBYTE
5989 WCHAR *wn = NULL;
5990
5991 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005992 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005993#endif
5994
5995 if (mch_isdir(n))
5996 {
5997 char TempName[_MAX_PATH + 16] = "";
5998#ifdef FEAT_MBYTE
5999 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6000#endif
6001
6002 if (p & R_OK)
6003 {
6004 /* Read check is performed by seeing if we can do a find file on
6005 * the directory for any file. */
6006#ifdef FEAT_MBYTE
6007 if (wn != NULL)
6008 {
6009 int i;
6010 WIN32_FIND_DATAW d;
6011
6012 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6013 TempNameW[i] = wn[i];
6014 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6015 TempNameW[i++] = '\\';
6016 TempNameW[i++] = '*';
6017 TempNameW[i++] = 0;
6018
6019 hFile = FindFirstFileW(TempNameW, &d);
6020 if (hFile == INVALID_HANDLE_VALUE)
6021 {
6022 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6023 goto getout;
6024
6025 /* Retry with non-wide function (for Windows 98). */
6026 vim_free(wn);
6027 wn = NULL;
6028 }
6029 else
6030 (void)FindClose(hFile);
6031 }
6032 if (wn == NULL)
6033#endif
6034 {
6035 char *pch;
6036 WIN32_FIND_DATA d;
6037
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006038 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006039 pch = TempName + STRLEN(TempName) - 1;
6040 if (*pch != '\\' && *pch != '/')
6041 *++pch = '\\';
6042 *++pch = '*';
6043 *++pch = NUL;
6044
6045 hFile = FindFirstFile(TempName, &d);
6046 if (hFile == INVALID_HANDLE_VALUE)
6047 goto getout;
6048 (void)FindClose(hFile);
6049 }
6050 }
6051
6052 if (p & W_OK)
6053 {
6054 /* Trying to create a temporary file in the directory should catch
6055 * directories on read-only network shares. However, in
6056 * directories whose ACL allows writes but denies deletes will end
6057 * up keeping the temporary file :-(. */
6058#ifdef FEAT_MBYTE
6059 if (wn != NULL)
6060 {
6061 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6062 {
6063 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6064 goto getout;
6065
6066 /* Retry with non-wide function (for Windows 98). */
6067 vim_free(wn);
6068 wn = NULL;
6069 }
6070 else
6071 DeleteFileW(TempNameW);
6072 }
6073 if (wn == NULL)
6074#endif
6075 {
6076 if (!GetTempFileName(n, "VIM", 0, TempName))
6077 goto getout;
6078 mch_remove((char_u *)TempName);
6079 }
6080 }
6081 }
6082 else
6083 {
6084 /* Trying to open the file for the required access does ACL, read-only
6085 * network share, and file attribute checks. */
6086 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6087 | ((p & R_OK) ? GENERIC_READ : 0);
6088#ifdef FEAT_MBYTE
6089 if (wn != NULL)
6090 {
6091 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6092 if (hFile == INVALID_HANDLE_VALUE
6093 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6094 {
6095 /* Retry with non-wide function (for Windows 98). */
6096 vim_free(wn);
6097 wn = NULL;
6098 }
6099 }
6100 if (wn == NULL)
6101#endif
6102 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6103 if (hFile == INVALID_HANDLE_VALUE)
6104 goto getout;
6105 CloseHandle(hFile);
6106 }
6107
6108 retval = 0; /* success */
6109getout:
6110#ifdef FEAT_MBYTE
6111 vim_free(wn);
6112#endif
6113 return retval;
6114}
6115
6116#if defined(FEAT_MBYTE) || defined(PROTO)
6117/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006118 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006119 */
6120 int
6121mch_open(char *name, int flags, int mode)
6122{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006123 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6124# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006125 WCHAR *wn;
6126 int f;
6127
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006128 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006130 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006131 if (wn != NULL)
6132 {
6133 f = _wopen(wn, flags, mode);
6134 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006135 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006136 return f;
6137 /* Retry with non-wide function (for Windows 98). Can't use
6138 * GetLastError() here and it's unclear what errno gets set to if
6139 * the _wopen() fails for missing wide functions. */
6140 }
6141 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006142# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006144 /* open() can open a file which name is longer than _MAX_PATH bytes
6145 * and shorter than _MAX_PATH characters successfully, but sometimes it
6146 * causes unexpected error in another part. We make it an error explicitly
6147 * here. */
6148 if (strlen(name) >= _MAX_PATH)
6149 return -1;
6150
Bram Moolenaar071d4272004-06-13 20:20:40 +00006151 return open(name, flags, mode);
6152}
6153
6154/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006155 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006156 */
6157 FILE *
6158mch_fopen(char *name, char *mode)
6159{
6160 WCHAR *wn, *wm;
6161 FILE *f = NULL;
6162
6163 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6164# ifdef __BORLANDC__
6165 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6166 && g_PlatformId == VER_PLATFORM_WIN32_NT
6167# endif
6168 )
6169 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006170# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006171 /* Work around an annoying assertion in the Microsoft debug CRT
6172 * when mode's text/binary setting doesn't match _get_fmode(). */
6173 char newMode = mode[strlen(mode) - 1];
6174 int oldMode = 0;
6175
6176 _get_fmode(&oldMode);
6177 if (newMode == 't')
6178 _set_fmode(_O_TEXT);
6179 else if (newMode == 'b')
6180 _set_fmode(_O_BINARY);
6181# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006182 wn = enc_to_utf16(name, NULL);
6183 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006184 if (wn != NULL && wm != NULL)
6185 f = _wfopen(wn, wm);
6186 vim_free(wn);
6187 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006188
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006189# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006190 _set_fmode(oldMode);
6191# endif
6192
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006193 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006194 return f;
6195 /* Retry with non-wide function (for Windows 98). Can't use
6196 * GetLastError() here and it's unclear what errno gets set to if
6197 * the _wfopen() fails for missing wide functions. */
6198 }
6199
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006200 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6201 * and shorter than _MAX_PATH characters successfully, but sometimes it
6202 * causes unexpected error in another part. We make it an error explicitly
6203 * here. */
6204 if (strlen(name) >= _MAX_PATH)
6205 return NULL;
6206
Bram Moolenaar071d4272004-06-13 20:20:40 +00006207 return fopen(name, mode);
6208}
6209#endif
6210
6211#ifdef FEAT_MBYTE
6212/*
6213 * SUB STREAM (aka info stream) handling:
6214 *
6215 * NTFS can have sub streams for each file. Normal contents of file is
6216 * stored in the main stream, and extra contents (author information and
6217 * title and so on) can be stored in sub stream. After Windows 2000, user
6218 * can access and store those informations in sub streams via explorer's
6219 * property menuitem in right click menu. Those informations in sub streams
6220 * were lost when copying only the main stream. So we have to copy sub
6221 * streams.
6222 *
6223 * Incomplete explanation:
6224 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6225 * More useful info and an example:
6226 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6227 */
6228
6229/*
6230 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6231 * and write to stream "substream" of file "to".
6232 * Errors are ignored.
6233 */
6234 static void
6235copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6236{
6237 HANDLE hTo;
6238 WCHAR *to_name;
6239
6240 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6241 wcscpy(to_name, to);
6242 wcscat(to_name, substream);
6243
6244 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6245 FILE_ATTRIBUTE_NORMAL, NULL);
6246 if (hTo != INVALID_HANDLE_VALUE)
6247 {
6248 long done;
6249 DWORD todo;
6250 DWORD readcnt, written;
6251 char buf[4096];
6252
6253 /* Copy block of bytes at a time. Abort when something goes wrong. */
6254 for (done = 0; done < len; done += written)
6255 {
6256 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006257 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6258 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006259 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6260 FALSE, FALSE, context)
6261 || readcnt != todo
6262 || !WriteFile(hTo, buf, todo, &written, NULL)
6263 || written != todo)
6264 break;
6265 }
6266 CloseHandle(hTo);
6267 }
6268
6269 free(to_name);
6270}
6271
6272/*
6273 * Copy info streams from file "from" to file "to".
6274 */
6275 static void
6276copy_infostreams(char_u *from, char_u *to)
6277{
6278 WCHAR *fromw;
6279 WCHAR *tow;
6280 HANDLE sh;
6281 WIN32_STREAM_ID sid;
6282 int headersize;
6283 WCHAR streamname[_MAX_PATH];
6284 DWORD readcount;
6285 void *context = NULL;
6286 DWORD lo, hi;
6287 int len;
6288
6289 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006290 fromw = enc_to_utf16(from, NULL);
6291 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006292 if (fromw != NULL && tow != NULL)
6293 {
6294 /* Open the file for reading. */
6295 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6296 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6297 if (sh != INVALID_HANDLE_VALUE)
6298 {
6299 /* Use BackupRead() to find the info streams. Repeat until we
6300 * have done them all.*/
6301 for (;;)
6302 {
6303 /* Get the header to find the length of the stream name. If
6304 * the "readcount" is zero we have done all info streams. */
6305 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006306 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6308 &readcount, FALSE, FALSE, &context)
6309 || readcount == 0)
6310 break;
6311
6312 /* We only deal with streams that have a name. The normal
6313 * file data appears to be without a name, even though docs
6314 * suggest it is called "::$DATA". */
6315 if (sid.dwStreamNameSize > 0)
6316 {
6317 /* Read the stream name. */
6318 if (!BackupRead(sh, (LPBYTE)streamname,
6319 sid.dwStreamNameSize,
6320 &readcount, FALSE, FALSE, &context))
6321 break;
6322
6323 /* Copy an info stream with a name ":anything:$DATA".
6324 * Skip "::$DATA", it has no stream name (examples suggest
6325 * it might be used for the normal file contents).
6326 * Note that BackupRead() counts bytes, but the name is in
6327 * wide characters. */
6328 len = readcount / sizeof(WCHAR);
6329 streamname[len] = 0;
6330 if (len > 7 && wcsicmp(streamname + len - 6,
6331 L":$DATA") == 0)
6332 {
6333 streamname[len - 6] = 0;
6334 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006335 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336 }
6337 }
6338
6339 /* Advance to the next stream. We might try seeking too far,
6340 * but BackupSeek() doesn't skip over stream borders, thus
6341 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006342 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006343 &lo, &hi, &context);
6344 }
6345
6346 /* Clear the context. */
6347 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6348
6349 CloseHandle(sh);
6350 }
6351 }
6352 vim_free(fromw);
6353 vim_free(tow);
6354}
6355#endif
6356
6357/*
6358 * Copy file attributes from file "from" to file "to".
6359 * For Windows NT and later we copy info streams.
6360 * Always returns zero, errors are ignored.
6361 */
6362 int
6363mch_copy_file_attribute(char_u *from, char_u *to)
6364{
6365#ifdef FEAT_MBYTE
6366 /* File streams only work on Windows NT and later. */
6367 PlatformId();
6368 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6369 copy_infostreams(from, to);
6370#endif
6371 return 0;
6372}
6373
6374#if defined(MYRESETSTKOFLW) || defined(PROTO)
6375/*
6376 * Recreate a destroyed stack guard page in win32.
6377 * Written by Benjamin Peterson.
6378 */
6379
6380/* These magic numbers are from the MS header files */
6381#define MIN_STACK_WIN9X 17
6382#define MIN_STACK_WINNT 2
6383
6384/*
6385 * This function does the same thing as _resetstkoflw(), which is only
6386 * available in DevStudio .net and later.
6387 * Returns 0 for failure, 1 for success.
6388 */
6389 int
6390myresetstkoflw(void)
6391{
6392 BYTE *pStackPtr;
6393 BYTE *pGuardPage;
6394 BYTE *pStackBase;
6395 BYTE *pLowestPossiblePage;
6396 MEMORY_BASIC_INFORMATION mbi;
6397 SYSTEM_INFO si;
6398 DWORD nPageSize;
6399 DWORD dummy;
6400
6401 /* This code will not work on win32s. */
6402 PlatformId();
6403 if (g_PlatformId == VER_PLATFORM_WIN32s)
6404 return 0;
6405
6406 /* We need to know the system page size. */
6407 GetSystemInfo(&si);
6408 nPageSize = si.dwPageSize;
6409
6410 /* ...and the current stack pointer */
6411 pStackPtr = (BYTE*)_alloca(1);
6412
6413 /* ...and the base of the stack. */
6414 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6415 return 0;
6416 pStackBase = (BYTE*)mbi.AllocationBase;
6417
6418 /* ...and the page thats min_stack_req pages away from stack base; this is
6419 * the lowest page we could use. */
6420 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6421 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6422
6423 /* On Win95, we want the next page down from the end of the stack. */
6424 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6425 {
6426 /* Find the page that's only 1 page down from the page that the stack
6427 * ptr is in. */
6428 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6429 / (DWORD)nPageSize) - 1));
6430 if (pGuardPage < pLowestPossiblePage)
6431 return 0;
6432
6433 /* Apply the noaccess attribute to the page -- there's no guard
6434 * attribute in win95-type OSes. */
6435 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6436 return 0;
6437 }
6438 else
6439 {
6440 /* On NT, however, we want the first committed page in the stack Start
6441 * at the stack base and move forward through memory until we find a
6442 * committed block. */
6443 BYTE *pBlock = pStackBase;
6444
Bram Moolenaara466c992005-07-09 21:03:22 +00006445 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006446 {
6447 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6448 return 0;
6449
6450 pBlock += mbi.RegionSize;
6451
6452 if (mbi.State & MEM_COMMIT)
6453 break;
6454 }
6455
6456 /* mbi now describes the first committed block in the stack. */
6457 if (mbi.Protect & PAGE_GUARD)
6458 return 1;
6459
6460 /* decide where the guard page should start */
6461 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6462 pGuardPage = pLowestPossiblePage;
6463 else
6464 pGuardPage = (BYTE*)mbi.BaseAddress;
6465
6466 /* allocate the guard page */
6467 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6468 return 0;
6469
6470 /* apply the guard attribute to the page */
6471 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6472 &dummy))
6473 return 0;
6474 }
6475
6476 return 1;
6477}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006478#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006480
6481#if defined(FEAT_MBYTE) || defined(PROTO)
6482/*
6483 * The command line arguments in UCS2
6484 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006485static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006486static LPWSTR *ArglistW = NULL;
6487static int global_argc = 0;
6488static char **global_argv;
6489
6490static int used_file_argc = 0; /* last argument in global_argv[] used
6491 for the argument list. */
6492static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6493 command line arguments added to
6494 the argument list */
6495static int used_file_count = 0; /* nr of entries in used_file_indexes */
6496static int used_file_literal = FALSE; /* take file names literally */
6497static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006498static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006499static int used_alist_count = 0;
6500
6501
6502/*
6503 * Get the command line arguments. Unicode version.
6504 * Returns argc. Zero when something fails.
6505 */
6506 int
6507get_cmd_argsW(char ***argvp)
6508{
6509 char **argv = NULL;
6510 int argc = 0;
6511 int i;
6512
Bram Moolenaar14993322014-09-09 12:25:33 +02006513 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006514 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6515 if (ArglistW != NULL)
6516 {
6517 argv = malloc((nArgsW + 1) * sizeof(char *));
6518 if (argv != NULL)
6519 {
6520 argc = nArgsW;
6521 argv[argc] = NULL;
6522 for (i = 0; i < argc; ++i)
6523 {
6524 int len;
6525
6526 /* Convert each Unicode argument to the current codepage. */
6527 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006528 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006529 (LPSTR *)&argv[i], &len, 0, 0);
6530 if (argv[i] == NULL)
6531 {
6532 /* Out of memory, clear everything. */
6533 while (i > 0)
6534 free(argv[--i]);
6535 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006536 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006537 argc = 0;
6538 }
6539 }
6540 }
6541 }
6542
6543 global_argc = argc;
6544 global_argv = argv;
6545 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006546 {
6547 if (used_file_indexes != NULL)
6548 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006549 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006550 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006551
6552 if (argvp != NULL)
6553 *argvp = argv;
6554 return argc;
6555}
6556
6557 void
6558free_cmd_argsW(void)
6559{
6560 if (ArglistW != NULL)
6561 {
6562 GlobalFree(ArglistW);
6563 ArglistW = NULL;
6564 }
6565}
6566
6567/*
6568 * Remember "name" is an argument that was added to the argument list.
6569 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6570 * is called.
6571 */
6572 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006573used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006574{
6575 int i;
6576
6577 if (used_file_indexes == NULL)
6578 return;
6579 for (i = used_file_argc + 1; i < global_argc; ++i)
6580 if (STRCMP(global_argv[i], name) == 0)
6581 {
6582 used_file_argc = i;
6583 used_file_indexes[used_file_count++] = i;
6584 break;
6585 }
6586 used_file_literal = literal;
6587 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006588 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006589}
6590
6591/*
6592 * Remember the length of the argument list as it was. If it changes then we
6593 * leave it alone when 'encoding' is set.
6594 */
6595 void
6596set_alist_count(void)
6597{
6598 used_alist_count = GARGCOUNT;
6599}
6600
6601/*
6602 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6603 * has been changed while starting up. Use the UCS-2 command line arguments
6604 * and convert them to 'encoding'.
6605 */
6606 void
6607fix_arg_enc(void)
6608{
6609 int i;
6610 int idx;
6611 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006612 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006613
6614 /* Safety checks:
6615 * - if argument count differs between the wide and non-wide argument
6616 * list, something must be wrong.
6617 * - the file name arguments must have been located.
6618 * - the length of the argument list wasn't changed by the user.
6619 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006620 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006621 || ArglistW == NULL
6622 || used_file_indexes == NULL
6623 || used_file_count == 0
6624 || used_alist_count != GARGCOUNT)
6625 return;
6626
Bram Moolenaar86b68352004-12-27 21:59:20 +00006627 /* Remember the buffer numbers for the arguments. */
6628 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6629 if (fnum_list == NULL)
6630 return; /* out of memory */
6631 for (i = 0; i < GARGCOUNT; ++i)
6632 fnum_list[i] = GARGLIST[i].ae_fnum;
6633
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006634 /* Clear the argument list. Make room for the new arguments. */
6635 alist_clear(&global_alist);
6636 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006637 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006638
6639 for (i = 0; i < used_file_count; ++i)
6640 {
6641 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006642 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006643 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006644 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006645#ifdef FEAT_DIFF
6646 /* When using diff mode may need to concatenate file name to
6647 * directory name. Just like it's done in main(). */
6648 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6649 && !mch_isdir(alist_name(&GARGLIST[0])))
6650 {
6651 char_u *r;
6652
6653 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6654 if (r != NULL)
6655 {
6656 vim_free(str);
6657 str = r;
6658 }
6659 }
6660#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006661 /* Re-use the old buffer by renaming it. When not using literal
6662 * names it's done by alist_expand() below. */
6663 if (used_file_literal)
6664 buf_set_name(fnum_list[i], str);
6665
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006666 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006667 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006668 }
6669
6670 if (!used_file_literal)
6671 {
6672 /* Now expand wildcards in the arguments. */
6673 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6674 * filename characters but are excluded from 'isfname' to make
6675 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6676 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006677 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006678 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6679 }
6680
6681 /* If wildcard expansion failed, we are editing the first file of the
6682 * arglist and there is no file name: Edit the first argument now. */
6683 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6684 {
6685 do_cmdline_cmd((char_u *)":rewind");
6686 if (GARGCOUNT == 1 && used_file_full_path)
6687 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6688 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006689
6690 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006691}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006692#endif