fork for IVI
[profile/ivi/vim.git] / src / os_mswin.c
1 /* 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 /*
11  * os_mswin.c
12  *
13  * Routines common to both Win16 and Win32.
14  */
15
16 #ifdef WIN16
17 # ifdef __BORLANDC__
18 #  pragma warn -par
19 #  pragma warn -ucp
20 #  pragma warn -use
21 #  pragma warn -aus
22 # endif
23 #endif
24
25 #include "vim.h"
26
27 #ifdef WIN16
28 # define SHORT_FNAME            /* always 8.3 file name */
29 # include <dos.h>
30 # include <string.h>
31 #endif
32 #include <sys/types.h>
33 #include <signal.h>
34 #include <limits.h>
35 #include <process.h>
36
37 #undef chdir
38 #ifdef __GNUC__
39 # ifndef __MINGW32__
40 #  include <dirent.h>
41 # endif
42 #else
43 # include <direct.h>
44 #endif
45
46 #if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
47 # include <shellapi.h>
48 #endif
49
50 #if defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)
51 # include <dlgs.h>
52 # ifdef WIN3264
53 #  include <winspool.h>
54 # else
55 #  include <print.h>
56 # endif
57 # include <commdlg.h>
58 #endif
59
60 #ifdef __MINGW32__
61 # ifndef FROM_LEFT_1ST_BUTTON_PRESSED
62 #  define FROM_LEFT_1ST_BUTTON_PRESSED    0x0001
63 # endif
64 # ifndef RIGHTMOST_BUTTON_PRESSED
65 #  define RIGHTMOST_BUTTON_PRESSED        0x0002
66 # endif
67 # ifndef FROM_LEFT_2ND_BUTTON_PRESSED
68 #  define FROM_LEFT_2ND_BUTTON_PRESSED    0x0004
69 # endif
70 # ifndef FROM_LEFT_3RD_BUTTON_PRESSED
71 #  define FROM_LEFT_3RD_BUTTON_PRESSED    0x0008
72 # endif
73 # ifndef FROM_LEFT_4TH_BUTTON_PRESSED
74 #  define FROM_LEFT_4TH_BUTTON_PRESSED    0x0010
75 # endif
76
77 /*
78  * EventFlags
79  */
80 # ifndef MOUSE_MOVED
81 #  define MOUSE_MOVED   0x0001
82 # endif
83 # ifndef DOUBLE_CLICK
84 #  define DOUBLE_CLICK  0x0002
85 # endif
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
95 typedef int BOOL;
96 typedef int CALLBACK;
97 typedef int COLORREF;
98 typedef int CONSOLE_CURSOR_INFO;
99 typedef int COORD;
100 typedef int DWORD;
101 typedef int ENUMLOGFONT;
102 typedef int HANDLE;
103 typedef int HDC;
104 typedef int HFONT;
105 typedef int HICON;
106 typedef int HWND;
107 typedef int INPUT_RECORD;
108 typedef int KEY_EVENT_RECORD;
109 typedef int LOGFONT;
110 typedef int LPARAM;
111 typedef int LPBOOL;
112 typedef int LPCSTR;
113 typedef int LPCWSTR;
114 typedef int LPSTR;
115 typedef int LPTSTR;
116 typedef int LPWSTR;
117 typedef int LRESULT;
118 typedef int MOUSE_EVENT_RECORD;
119 typedef int NEWTEXTMETRIC;
120 typedef int PACL;
121 typedef int PRINTDLG;
122 typedef int PSECURITY_DESCRIPTOR;
123 typedef int PSID;
124 typedef int SECURITY_INFORMATION;
125 typedef int SHORT;
126 typedef int SMALL_RECT;
127 typedef int TEXTMETRIC;
128 typedef int UINT;
129 typedef int WCHAR;
130 typedef int WORD;
131 typedef int WPARAM;
132 typedef void VOID;
133 #endif
134
135 /* Record all output and all keyboard & mouse input */
136 /* #define MCH_WRITE_DUMP */
137
138 #ifdef MCH_WRITE_DUMP
139 FILE* fdDump = NULL;
140 #endif
141
142 #ifdef WIN3264
143 extern DWORD g_PlatformId;
144 #endif
145
146 #ifndef FEAT_GUI_MSWIN
147 extern char g_szOrigTitle[];
148 #endif
149
150 #ifdef FEAT_GUI
151 extern HWND s_hwnd;
152 #else
153 static HWND s_hwnd = 0;     /* console window handle, set by GetConsoleHwnd() */
154 #endif
155
156 extern int WSInitialized;
157
158 /* Don't generate prototypes here, because some systems do have these
159  * functions. */
160 #if defined(__GNUC__) && !defined(PROTO)
161 # ifndef __MINGW32__
162 int _stricoll(char *a, char *b)
163 {
164     // the ANSI-ish correct way is to use strxfrm():
165     char a_buff[512], b_buff[512];  // file names, so this is enough on Win32
166     strxfrm(a_buff, a, 512);
167     strxfrm(b_buff, b, 512);
168     return strcoll(a_buff, b_buff);
169 }
170
171 char * _fullpath(char *buf, char *fname, int len)
172 {
173     LPTSTR toss;
174
175     return (char *)GetFullPathName(fname, len, buf, &toss);
176 }
177 # endif
178
179 int _chdrive(int drive)
180 {
181     char temp [3] = "-:";
182     temp[0] = drive + 'A' - 1;
183     return !SetCurrentDirectory(temp);
184 }
185 #else
186 # ifdef __BORLANDC__
187 /* being a more ANSI compliant compiler, BorlandC doesn't define _stricoll:
188  * but it does in BC 5.02! */
189 #  if __BORLANDC__ < 0x502
190 int _stricoll(char *a, char *b)
191 {
192 #   if 1
193     // this is fast but not correct:
194     return stricmp(a, b);
195 #   else
196     // the ANSI-ish correct way is to use strxfrm():
197     char a_buff[512], b_buff[512];  // file names, so this is enough on Win32
198     strxfrm(a_buff, a, 512);
199     strxfrm(b_buff, b, 512);
200     return strcoll(a_buff, b_buff);
201 #   endif
202 }
203 #  endif
204 # endif
205 #endif
206
207
208 #if defined(FEAT_GUI_MSWIN) || defined(PROTO)
209 /*
210  * GUI version of mch_exit().
211  * Shut down and exit with status `r'
212  * Careful: mch_exit() may be called before mch_init()!
213  */
214     void
215 mch_exit(int r)
216 {
217     display_errors();
218
219     ml_close_all(TRUE);         /* remove all memfiles */
220
221 # ifdef FEAT_OLE
222     UninitOLE();
223 # endif
224 # ifdef FEAT_NETBEANS_INTG
225     if (WSInitialized)
226     {
227         WSInitialized = FALSE;
228         WSACleanup();
229     }
230 # endif
231 #ifdef DYNAMIC_GETTEXT
232     dyn_libintl_end();
233 #endif
234
235     if (gui.in_use)
236         gui_exit(r);
237
238 #ifdef EXITFREE
239     free_all_mem();
240 #endif
241
242     exit(r);
243 }
244
245 #endif /* FEAT_GUI_MSWIN */
246
247
248 /*
249  * Init the tables for toupper() and tolower().
250  */
251     void
252 mch_early_init(void)
253 {
254     int         i;
255
256 #ifdef WIN3264
257     PlatformId();
258 #endif
259
260     /* Init the tables for toupper() and tolower() */
261     for (i = 0; i < 256; ++i)
262         toupper_tab[i] = tolower_tab[i] = i;
263 #ifdef WIN3264
264     CharUpperBuff(toupper_tab, 256);
265     CharLowerBuff(tolower_tab, 256);
266 #else
267     AnsiUpperBuff(toupper_tab, 256);
268     AnsiLowerBuff(tolower_tab, 256);
269 #endif
270
271 #if defined(FEAT_MBYTE) && !defined(FEAT_GUI)
272     (void)get_cmd_argsW(NULL);
273 #endif
274 }
275
276
277 /*
278  * Return TRUE if the input comes from a terminal, FALSE otherwise.
279  */
280     int
281 mch_input_isatty()
282 {
283 #ifdef FEAT_GUI_MSWIN
284     return OK;      /* GUI always has a tty */
285 #else
286     if (isatty(read_cmd_fd))
287         return TRUE;
288     return FALSE;
289 #endif
290 }
291
292 #ifdef FEAT_TITLE
293 /*
294  * mch_settitle(): set titlebar of our window
295  */
296     void
297 mch_settitle(
298     char_u *title,
299     char_u *icon)
300 {
301 # ifdef FEAT_GUI_MSWIN
302     gui_mch_settitle(title, icon);
303 # else
304     if (title != NULL)
305     {
306 #  ifdef FEAT_MBYTE
307         if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
308         {
309             /* Convert the title from 'encoding' to the active codepage. */
310             WCHAR       *wp = enc_to_utf16(title, NULL);
311             int n;
312
313             if (wp != NULL)
314             {
315                 n = SetConsoleTitleW(wp);
316                 vim_free(wp);
317                 if (n != 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
318                     return;
319             }
320         }
321 #  endif
322         SetConsoleTitle(title);
323     }
324 # endif
325 }
326
327
328 /*
329  * Restore the window/icon title.
330  * which is one of:
331  *  1: Just restore title
332  *  2: Just restore icon (which we don't have)
333  *  3: Restore title and icon (which we don't have)
334  */
335 /*ARGSUSED*/
336     void
337 mch_restore_title(
338     int which)
339 {
340 #ifndef FEAT_GUI_MSWIN
341     mch_settitle((which & 1) ? g_szOrigTitle : NULL, NULL);
342 #endif
343 }
344
345
346 /*
347  * Return TRUE if we can restore the title (we can)
348  */
349     int
350 mch_can_restore_title()
351 {
352     return TRUE;
353 }
354
355
356 /*
357  * Return TRUE if we can restore the icon title (we can't)
358  */
359     int
360 mch_can_restore_icon()
361 {
362     return FALSE;
363 }
364 #endif /* FEAT_TITLE */
365
366
367 /*
368  * Get absolute file name into buffer "buf" of length "len" bytes,
369  * turning all '/'s into '\\'s and getting the correct case of each component
370  * of the file name.  Append a (back)slash to a directory name.
371  * When 'shellslash' set do it the other way around.
372  * Return OK or FAIL.
373  */
374 /*ARGSUSED*/
375     int
376 mch_FullName(
377     char_u      *fname,
378     char_u      *buf,
379     int         len,
380     int         force)
381 {
382     int         nResult = FAIL;
383
384 #ifdef __BORLANDC__
385     if (*fname == NUL) /* Borland behaves badly here - make it consistent */
386         nResult = mch_dirname(buf, len);
387     else
388 #endif
389     {
390 #ifdef FEAT_MBYTE
391         if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
392 # ifdef __BORLANDC__
393                 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
394                 && g_PlatformId == VER_PLATFORM_WIN32_NT
395 # endif
396            )
397         {
398             WCHAR       *wname;
399             WCHAR       wbuf[MAX_PATH];
400             char_u      *cname = NULL;
401
402             /* Use the wide function:
403              * - convert the fname from 'encoding' to UCS2.
404              * - invoke _wfullpath()
405              * - convert the result from UCS2 to 'encoding'.
406              */
407             wname = enc_to_utf16(fname, NULL);
408             if (wname != NULL && _wfullpath(wbuf, wname, MAX_PATH - 1) != NULL)
409             {
410                 cname = utf16_to_enc((short_u *)wbuf, NULL);
411                 if (cname != NULL)
412                 {
413                     vim_strncpy(buf, cname, len - 1);
414                     nResult = OK;
415                 }
416             }
417             vim_free(wname);
418             vim_free(cname);
419         }
420         if (nResult == FAIL)        /* fall back to non-wide function */
421 #endif
422         {
423             if (_fullpath(buf, fname, len - 1) == NULL)
424             {
425                 /* failed, use relative path name */
426                 vim_strncpy(buf, fname, len - 1);
427             }
428             else
429                 nResult = OK;
430         }
431     }
432
433 #ifdef USE_FNAME_CASE
434     fname_case(buf, len);
435 #else
436     slash_adjust(buf);
437 #endif
438
439     return nResult;
440 }
441
442
443 /*
444  * Return TRUE if "fname" does not depend on the current directory.
445  */
446     int
447 mch_isFullName(char_u *fname)
448 {
449     char szName[_MAX_PATH + 1];
450
451     /* A name like "d:/foo" and "//server/share" is absolute */
452     if ((fname[0] && fname[1] == ':' && (fname[2] == '/' || fname[2] == '\\'))
453             || (fname[0] == fname[1] && (fname[0] == '/' || fname[0] == '\\')))
454         return TRUE;
455
456     /* A name that can't be made absolute probably isn't absolute. */
457     if (mch_FullName(fname, szName, _MAX_PATH, FALSE) == FAIL)
458         return FALSE;
459
460     return pathcmp(fname, szName, -1) == 0;
461 }
462
463 /*
464  * Replace all slashes by backslashes.
465  * This used to be the other way around, but MS-DOS sometimes has problems
466  * with slashes (e.g. in a command name).  We can't have mixed slashes and
467  * backslashes, because comparing file names will not work correctly.  The
468  * commands that use a file name should try to avoid the need to type a
469  * backslash twice.
470  * When 'shellslash' set do it the other way around.
471  */
472     void
473 slash_adjust(p)
474     char_u  *p;
475 {
476     while (*p)
477     {
478         if (*p == psepcN)
479             *p = psepc;
480         mb_ptr_adv(p);
481     }
482 }
483
484
485 /*
486  * stat() can't handle a trailing '/' or '\', remove it first.
487  */
488     int
489 vim_stat(const char *name, struct stat *stp)
490 {
491     char        buf[_MAX_PATH + 1];
492     char        *p;
493
494     vim_strncpy((char_u *)buf, (char_u *)name, _MAX_PATH);
495     p = buf + strlen(buf);
496     if (p > buf)
497         mb_ptr_back(buf, p);
498     if (p > buf && (*p == '\\' || *p == '/') && p[-1] != ':')
499         *p = NUL;
500 #ifdef FEAT_MBYTE
501     if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
502 # ifdef __BORLANDC__
503             /* Wide functions of Borland C 5.5 do not work on Windows 98. */
504             && g_PlatformId == VER_PLATFORM_WIN32_NT
505 # endif
506        )
507     {
508         WCHAR   *wp = enc_to_utf16(buf, NULL);
509         int     n;
510
511         if (wp != NULL)
512         {
513             n = _wstat(wp, (struct _stat *)stp);
514             vim_free(wp);
515             if (n >= 0)
516                 return n;
517             /* Retry with non-wide function (for Windows 98). Can't use
518              * GetLastError() here and it's unclear what errno gets set to if
519              * the _wstat() fails for missing wide functions. */
520         }
521     }
522 #endif
523     return stat(buf, stp);
524 }
525
526 #if defined(FEAT_GUI_MSWIN) || defined(PROTO)
527 /*ARGSUSED*/
528     void
529 mch_settmode(int tmode)
530 {
531     /* nothing to do */
532 }
533
534     int
535 mch_get_shellsize(void)
536 {
537     /* never used */
538     return OK;
539 }
540
541     void
542 mch_set_shellsize(void)
543 {
544     /* never used */
545 }
546
547 /*
548  * Rows and/or Columns has changed.
549  */
550     void
551 mch_new_shellsize(void)
552 {
553     /* never used */
554 }
555
556 #endif
557
558 /*
559  * We have no job control, so fake it by starting a new shell.
560  */
561     void
562 mch_suspend()
563 {
564     suspend_shell();
565 }
566
567 #if defined(USE_MCH_ERRMSG) || defined(PROTO)
568
569 #ifdef display_errors
570 # undef display_errors
571 #endif
572
573 /*
574  * Display the saved error message(s).
575  */
576     void
577 display_errors()
578 {
579     char *p;
580
581     if (error_ga.ga_data != NULL)
582     {
583         /* avoid putting up a message box with blanks only */
584         for (p = (char *)error_ga.ga_data; *p; ++p)
585             if (!isspace(*p))
586             {
587                 (void)gui_mch_dialog(
588 #ifdef FEAT_GUI
589                                      gui.starting ? VIM_INFO :
590 #endif
591                                              VIM_ERROR,
592 #ifdef FEAT_GUI
593                                      gui.starting ? (char_u *)_("Message") :
594 #endif
595                                              (char_u *)_("Error"),
596                                      p, (char_u *)_("&Ok"), 1, NULL, FALSE);
597                 break;
598             }
599         ga_clear(&error_ga);
600     }
601 }
602 #endif
603
604
605 /*
606  * Return TRUE if "p" contain a wildcard that can be expanded by
607  * dos_expandpath().
608  */
609     int
610 mch_has_exp_wildcard(char_u *p)
611 {
612     for ( ; *p; mb_ptr_adv(p))
613     {
614         if (vim_strchr((char_u *)"?*[", *p) != NULL
615                 || (*p == '~' && p[1] != NUL))
616             return TRUE;
617     }
618     return FALSE;
619 }
620
621 /*
622  * Return TRUE if "p" contain a wildcard or a "~1" kind of thing (could be a
623  * shortened file name).
624  */
625     int
626 mch_has_wildcard(char_u *p)
627 {
628     for ( ; *p; mb_ptr_adv(p))
629     {
630         if (vim_strchr((char_u *)
631 #  ifdef VIM_BACKTICK
632                                     "?*$[`"
633 #  else
634                                     "?*$["
635 #  endif
636                                                 , *p) != NULL
637                 || (*p == '~' && p[1] != NUL))
638             return TRUE;
639     }
640     return FALSE;
641 }
642
643
644 /*
645  * The normal _chdir() does not change the default drive.  This one does.
646  * Returning 0 implies success; -1 implies failure.
647  */
648     int
649 mch_chdir(char *path)
650 {
651     if (path[0] == NUL)         /* just checking... */
652         return -1;
653
654     if (p_verbose >= 5)
655     {
656         verbose_enter();
657         smsg((char_u *)"chdir(%s)", path);
658         verbose_leave();
659     }
660     if (isalpha(path[0]) && path[1] == ':')     /* has a drive name */
661     {
662         /* If we can change to the drive, skip that part of the path.  If we
663          * can't then the current directory may be invalid, try using chdir()
664          * with the whole path. */
665         if (_chdrive(TOLOWER_ASC(path[0]) - 'a' + 1) == 0)
666             path += 2;
667     }
668
669     if (*path == NUL)           /* drive name only */
670         return 0;
671
672 #ifdef FEAT_MBYTE
673     if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
674     {
675         WCHAR   *p = enc_to_utf16(path, NULL);
676         int     n;
677
678         if (p != NULL)
679         {
680             n = _wchdir(p);
681             vim_free(p);
682             if (n == 0)
683                 return 0;
684             /* Retry with non-wide function (for Windows 98). */
685         }
686     }
687 #endif
688
689     return chdir(path);        /* let the normal chdir() do the rest */
690 }
691
692
693 /*
694  * Switching off termcap mode is only allowed when Columns is 80, otherwise a
695  * crash may result.  It's always allowed on NT or when running the GUI.
696  */
697 /*ARGSUSED*/
698     int
699 can_end_termcap_mode(
700     int give_msg)
701 {
702 #ifdef FEAT_GUI_MSWIN
703     return TRUE;        /* GUI starts a new console anyway */
704 #else
705     if (g_PlatformId == VER_PLATFORM_WIN32_NT || Columns == 80)
706         return TRUE;
707     if (give_msg)
708         msg(_("'columns' is not 80, cannot execute external commands"));
709     return FALSE;
710 #endif
711 }
712
713 #ifdef FEAT_GUI_MSWIN
714 /*
715  * return non-zero if a character is available
716  */
717     int
718 mch_char_avail()
719 {
720     /* never used */
721     return TRUE;
722 }
723 #endif
724
725
726 /*
727  * set screen mode, always fails.
728  */
729 /*ARGSUSED*/
730     int
731 mch_screenmode(
732     char_u *arg)
733 {
734     EMSG(_(e_screenmode));
735     return FAIL;
736 }
737
738
739 #if defined(FEAT_LIBCALL) || defined(PROTO)
740 /*
741  * Call a DLL routine which takes either a string or int param
742  * and returns an allocated string.
743  * Return OK if it worked, FAIL if not.
744  */
745 # ifdef WIN3264
746 typedef LPTSTR (*MYSTRPROCSTR)(LPTSTR);
747 typedef LPTSTR (*MYINTPROCSTR)(int);
748 typedef int (*MYSTRPROCINT)(LPTSTR);
749 typedef int (*MYINTPROCINT)(int);
750 # else
751 typedef LPSTR (*MYSTRPROCSTR)(LPSTR);
752 typedef LPSTR (*MYINTPROCSTR)(int);
753 typedef int (*MYSTRPROCINT)(LPSTR);
754 typedef int (*MYINTPROCINT)(int);
755 # endif
756
757 # ifndef WIN16
758 /*
759  * Check if a pointer points to a valid NUL terminated string.
760  * Return the length of the string, including terminating NUL.
761  * Returns 0 for an invalid pointer, 1 for an empty string.
762  */
763     static size_t
764 check_str_len(char_u *str)
765 {
766     SYSTEM_INFO                 si;
767     MEMORY_BASIC_INFORMATION    mbi;
768     size_t                      length = 0;
769     size_t                      i;
770     const char                  *p;
771
772     /* get page size */
773     GetSystemInfo(&si);
774
775     /* get memory information */
776     if (VirtualQuery(str, &mbi, sizeof(mbi)))
777     {
778         /* pre cast these (typing savers) */
779         long_u dwStr = (long_u)str;
780         long_u dwBaseAddress = (long_u)mbi.BaseAddress;
781
782         /* get start address of page that str is on */
783         long_u strPage = dwStr - (dwStr - dwBaseAddress) % si.dwPageSize;
784
785         /* get length from str to end of page */
786         long_u pageLength = si.dwPageSize - (dwStr - strPage);
787
788         for (p = str; !IsBadReadPtr(p, (UINT)pageLength);
789                                   p += pageLength, pageLength = si.dwPageSize)
790             for (i = 0; i < pageLength; ++i, ++length)
791                 if (p[i] == NUL)
792                     return length + 1;
793     }
794
795     return 0;
796 }
797 # endif
798
799     int
800 mch_libcall(
801     char_u      *libname,
802     char_u      *funcname,
803     char_u      *argstring,     /* NULL when using a argint */
804     int         argint,
805     char_u      **string_result,/* NULL when using number_result */
806     int         *number_result)
807 {
808     HINSTANCE           hinstLib;
809     MYSTRPROCSTR        ProcAdd;
810     MYINTPROCSTR        ProcAddI;
811     char_u              *retval_str = NULL;
812     int                 retval_int = 0;
813     size_t              len;
814
815     BOOL fRunTimeLinkSuccess = FALSE;
816
817     // Get a handle to the DLL module.
818 # ifdef WIN16
819     hinstLib = LoadLibrary(libname);
820 # else
821     hinstLib = vimLoadLib(libname);
822 # endif
823
824     // If the handle is valid, try to get the function address.
825     if (hinstLib != NULL)
826     {
827 #ifdef HAVE_TRY_EXCEPT
828         __try
829         {
830 #endif
831         if (argstring != NULL)
832         {
833             /* Call with string argument */
834             ProcAdd = (MYSTRPROCSTR) GetProcAddress(hinstLib, funcname);
835             if ((fRunTimeLinkSuccess = (ProcAdd != NULL)) != 0)
836             {
837                 if (string_result == NULL)
838                     retval_int = ((MYSTRPROCINT)ProcAdd)(argstring);
839                 else
840                     retval_str = (ProcAdd)(argstring);
841             }
842         }
843         else
844         {
845             /* Call with number argument */
846             ProcAddI = (MYINTPROCSTR) GetProcAddress(hinstLib, funcname);
847             if ((fRunTimeLinkSuccess = (ProcAddI != NULL)) != 0)
848             {
849                 if (string_result == NULL)
850                     retval_int = ((MYINTPROCINT)ProcAddI)(argint);
851                 else
852                     retval_str = (ProcAddI)(argint);
853             }
854         }
855
856         // Save the string before we free the library.
857         // Assume that a "1" result is an illegal pointer.
858         if (string_result == NULL)
859             *number_result = retval_int;
860         else if (retval_str != NULL
861 # ifdef WIN16
862                 && retval_str != (char_u *)1
863                 && retval_str != (char_u *)-1
864                 && !IsBadStringPtr(retval_str, INT_MAX)
865                 && (len = strlen(retval_str) + 1) > 0
866 # else
867                 && (len = check_str_len(retval_str)) > 0
868 # endif
869                 )
870         {
871             *string_result = lalloc((long_u)len, TRUE);
872             if (*string_result != NULL)
873                 mch_memmove(*string_result, retval_str, len);
874         }
875
876 #ifdef HAVE_TRY_EXCEPT
877         }
878         __except(EXCEPTION_EXECUTE_HANDLER)
879         {
880             if (GetExceptionCode() == EXCEPTION_STACK_OVERFLOW)
881                 RESETSTKOFLW();
882             fRunTimeLinkSuccess = 0;
883         }
884 #endif
885
886         // Free the DLL module.
887         (void)FreeLibrary(hinstLib);
888     }
889
890     if (!fRunTimeLinkSuccess)
891     {
892         EMSG2(_(e_libcall), funcname);
893         return FAIL;
894     }
895
896     return OK;
897 }
898 #endif
899
900 #if defined(FEAT_MBYTE) || defined(PROTO)
901 /*
902  * Convert an UTF-8 string to UTF-16.
903  * "instr[inlen]" is the input.  "inlen" is in bytes.
904  * When "outstr" is NULL only return the number of UTF-16 words produced.
905  * Otherwise "outstr" must be a buffer of sufficient size.
906  * Returns the number of UTF-16 words produced.
907  */
908     int
909 utf8_to_utf16(char_u *instr, int inlen, short_u *outstr, int *unconvlenp)
910 {
911     int         outlen = 0;
912     char_u      *p = instr;
913     int         todo = inlen;
914     int         l;
915     int         ch;
916
917     while (todo > 0)
918     {
919         /* Only convert if we have a complete sequence. */
920         l = utf_ptr2len_len(p, todo);
921         if (l > todo)
922         {
923             /* Return length of incomplete sequence. */
924             if (unconvlenp != NULL)
925                 *unconvlenp = todo;
926             break;
927         }
928
929         ch = utf_ptr2char(p);
930         if (ch >= 0x10000)
931         {
932             /* non-BMP character, encoding with surrogate pairs */
933             ++outlen;
934             if (outstr != NULL)
935             {
936                 *outstr++ = (0xD800 - (0x10000 >> 10)) + (ch >> 10);
937                 *outstr++ = 0xDC00 | (ch & 0x3FF);
938             }
939         }
940         else if (outstr != NULL)
941             *outstr++ = ch;
942         ++outlen;
943         p += l;
944         todo -= l;
945     }
946
947     return outlen;
948 }
949
950 /*
951  * Convert an UTF-16 string to UTF-8.
952  * The input is "instr[inlen]" with "inlen" in number of UTF-16 words.
953  * When "outstr" is NULL only return the required number of bytes.
954  * Otherwise "outstr" must be a buffer of sufficient size.
955  * Return the number of bytes produced.
956  */
957     int
958 utf16_to_utf8(short_u *instr, int inlen, char_u *outstr)
959 {
960     int         outlen = 0;
961     int         todo = inlen;
962     short_u     *p = instr;
963     int         l;
964     int         ch, ch2;
965
966     while (todo > 0)
967     {
968         ch = *p;
969         if (ch >= 0xD800 && ch <= 0xDBFF && todo > 1)
970         {
971             /* surrogate pairs handling */
972             ch2 = p[1];
973             if (ch2 >= 0xDC00 && ch2 <= 0xDFFF)
974             {
975                 ch = ((ch - 0xD800) << 10) + (ch2 & 0x3FF) + 0x10000;
976                 ++p;
977                 --todo;
978             }
979         }
980         if (outstr != NULL)
981         {
982             l = utf_char2bytes(ch, outstr);
983             outstr += l;
984         }
985         else
986             l = utf_char2len(ch);
987         ++p;
988         outlen += l;
989         --todo;
990     }
991
992     return outlen;
993 }
994
995 /*
996  * Call MultiByteToWideChar() and allocate memory for the result.
997  * Returns the result in "*out[*outlen]" with an extra zero appended.
998  * "outlen" is in words.
999  */
1000     void
1001 MultiByteToWideChar_alloc(UINT cp, DWORD flags,
1002         LPCSTR in, int inlen,
1003         LPWSTR *out, int *outlen)
1004 {
1005     *outlen = MultiByteToWideChar(cp, flags, in, inlen, 0, 0);
1006     /* Add one one word to avoid a zero-length alloc(). */
1007     *out = (LPWSTR)alloc(sizeof(WCHAR) * (*outlen + 1));
1008     if (*out != NULL)
1009     {
1010         MultiByteToWideChar(cp, flags, in, inlen, *out, *outlen);
1011         (*out)[*outlen] = 0;
1012     }
1013 }
1014
1015 /*
1016  * Call WideCharToMultiByte() and allocate memory for the result.
1017  * Returns the result in "*out[*outlen]" with an extra NUL appended.
1018  */
1019     void
1020 WideCharToMultiByte_alloc(UINT cp, DWORD flags,
1021         LPCWSTR in, int inlen,
1022         LPSTR *out, int *outlen,
1023         LPCSTR def, LPBOOL useddef)
1024 {
1025     *outlen = WideCharToMultiByte(cp, flags, in, inlen, NULL, 0, def, useddef);
1026     /* Add one one byte to avoid a zero-length alloc(). */
1027     *out = alloc((unsigned)*outlen + 1);
1028     if (*out != NULL)
1029     {
1030         WideCharToMultiByte(cp, flags, in, inlen, *out, *outlen, def, useddef);
1031         (*out)[*outlen] = 0;
1032     }
1033 }
1034
1035 #endif /* FEAT_MBYTE */
1036
1037 #ifdef FEAT_CLIPBOARD
1038 /*
1039  * Clipboard stuff, for cutting and pasting text to other windows.
1040  */
1041
1042 /* Type used for the clipboard type of Vim's data. */
1043 typedef struct
1044 {
1045     int type;           /* MCHAR, MBLOCK or MLINE */
1046     int txtlen;         /* length of CF_TEXT in bytes */
1047     int ucslen;         /* length of CF_UNICODETEXT in words */
1048     int rawlen;         /* length of clip_star.format_raw, including encoding,
1049                            excluding terminating NUL */
1050 } VimClipType_t;
1051
1052 /*
1053  * Make vim the owner of the current selection.  Return OK upon success.
1054  */
1055 /*ARGSUSED*/
1056     int
1057 clip_mch_own_selection(VimClipboard *cbd)
1058 {
1059     /*
1060      * Never actually own the clipboard.  If another application sets the
1061      * clipboard, we don't want to think that we still own it.
1062      */
1063     return FAIL;
1064 }
1065
1066 /*
1067  * Make vim NOT the owner of the current selection.
1068  */
1069 /*ARGSUSED*/
1070     void
1071 clip_mch_lose_selection(VimClipboard *cbd)
1072 {
1073     /* Nothing needs to be done here */
1074 }
1075
1076 /*
1077  * Copy "str[*size]" into allocated memory, changing CR-NL to NL.
1078  * Return the allocated result and the size in "*size".
1079  * Returns NULL when out of memory.
1080  */
1081     static char_u *
1082 crnl_to_nl(const char_u *str, int *size)
1083 {
1084     int         pos = 0;
1085     int         str_len = *size;
1086     char_u      *ret;
1087     char_u      *retp;
1088
1089     /* Avoid allocating zero bytes, it generates an error message. */
1090     ret = lalloc((long_u)(str_len == 0 ? 1 : str_len), TRUE);
1091     if (ret != NULL)
1092     {
1093         retp = ret;
1094         for (pos = 0; pos < str_len; ++pos)
1095         {
1096             if (str[pos] == '\r' && str[pos + 1] == '\n')
1097             {
1098                 ++pos;
1099                 --(*size);
1100             }
1101             *retp++ = str[pos];
1102         }
1103     }
1104
1105     return ret;
1106 }
1107
1108 /*
1109  * Wait for another process to Close the Clipboard.
1110  * Returns TRUE for success.
1111  */
1112     static int
1113 vim_open_clipboard(void)
1114 {
1115     int delay = 10;
1116
1117     while (!OpenClipboard(NULL))
1118     {
1119         if (delay > 500)
1120             return FALSE;  /* waited too long, give up */
1121         Sleep(delay);
1122         delay *= 2;     /* wait for 10, 20, 40, 80, etc. msec */
1123     }
1124     return TRUE;
1125 }
1126
1127 /*
1128  * Get the current selection and put it in the clipboard register.
1129  *
1130  * NOTE: Must use GlobalLock/Unlock here to ensure Win32s compatibility.
1131  * On NT/W95 the clipboard data is a fixed global memory object and
1132  * so its handle = its pointer.
1133  * On Win32s, however, co-operation with the Win16 system means that
1134  * the clipboard data is moveable and its handle is not a pointer at all,
1135  * so we can't just cast the return value of GetClipboardData to (char_u*).
1136  * <VN>
1137  */
1138     void
1139 clip_mch_request_selection(VimClipboard *cbd)
1140 {
1141     VimClipType_t       metadata = { -1, -1, -1, -1 };
1142     HGLOBAL             hMem = NULL;
1143     char_u              *str = NULL;
1144 #if defined(FEAT_MBYTE) && defined(WIN3264)
1145     char_u              *to_free = NULL;
1146 #endif
1147 #ifdef FEAT_MBYTE
1148     HGLOBAL             rawh = NULL;
1149 #endif
1150     int                 str_size = 0;
1151     int                 maxlen;
1152     size_t              n;
1153
1154     /*
1155      * Don't pass GetActiveWindow() as an argument to OpenClipboard() because
1156      * then we can't paste back into the same window for some reason - webb.
1157      */
1158     if (!vim_open_clipboard())
1159         return;
1160
1161     /* Check for vim's own clipboard format first.  This only gets the type of
1162      * the data, still need to use CF_UNICODETEXT or CF_TEXT for the text. */
1163     if (IsClipboardFormatAvailable(cbd->format))
1164     {
1165         VimClipType_t   *meta_p;
1166         HGLOBAL         meta_h;
1167
1168         /* We have metadata on the clipboard; try to get it. */
1169         if ((meta_h = GetClipboardData(cbd->format)) != NULL
1170                 && (meta_p = (VimClipType_t *)GlobalLock(meta_h)) != NULL)
1171         {
1172             /* The size of "VimClipType_t" changed, "rawlen" was added later.
1173              * Only copy what is available for backwards compatibility. */
1174             n = sizeof(VimClipType_t);
1175             if (GlobalSize(meta_h) < n)
1176                 n = GlobalSize(meta_h);
1177             memcpy(&metadata, meta_p, n);
1178             GlobalUnlock(meta_h);
1179         }
1180     }
1181
1182 #ifdef FEAT_MBYTE
1183     /* Check for Vim's raw clipboard format first.  This is used without
1184      * conversion, but only if 'encoding' matches. */
1185     if (IsClipboardFormatAvailable(cbd->format_raw)
1186                                       && metadata.rawlen > (int)STRLEN(p_enc))
1187     {
1188         /* We have raw data on the clipboard; try to get it. */
1189         if ((rawh = GetClipboardData(cbd->format_raw)) != NULL)
1190         {
1191             char_u      *rawp;
1192
1193             rawp = (char_u *)GlobalLock(rawh);
1194             if (rawp != NULL && STRCMP(p_enc, rawp) == 0)
1195             {
1196                 n = STRLEN(p_enc) + 1;
1197                 str = rawp + n;
1198                 str_size = (int)(metadata.rawlen - n);
1199             }
1200             else
1201             {
1202                 GlobalUnlock(rawh);
1203                 rawh = NULL;
1204             }
1205         }
1206     }
1207     if (str == NULL)
1208     {
1209 #endif
1210
1211 #if defined(FEAT_MBYTE) && defined(WIN3264)
1212     /* Try to get the clipboard in Unicode if it's not an empty string. */
1213     if (IsClipboardFormatAvailable(CF_UNICODETEXT) && metadata.ucslen != 0)
1214     {
1215         HGLOBAL hMemW;
1216
1217         if ((hMemW = GetClipboardData(CF_UNICODETEXT)) != NULL)
1218         {
1219             WCHAR *hMemWstr = (WCHAR *)GlobalLock(hMemW);
1220
1221             /* Use the length of our metadata if possible, but limit it to the
1222              * GlobalSize() for safety. */
1223             maxlen = (int)(GlobalSize(hMemW) / sizeof(WCHAR));
1224             if (metadata.ucslen >= 0)
1225             {
1226                 if (metadata.ucslen > maxlen)
1227                     str_size = maxlen;
1228                 else
1229                     str_size = metadata.ucslen;
1230             }
1231             else
1232             {
1233                 for (str_size = 0; str_size < maxlen; ++str_size)
1234                     if (hMemWstr[str_size] == NUL)
1235                         break;
1236             }
1237             to_free = str = utf16_to_enc((short_u *)hMemWstr, &str_size);
1238             GlobalUnlock(hMemW);
1239         }
1240     }
1241     else
1242 #endif
1243     /* Get the clipboard in the Active codepage. */
1244     if (IsClipboardFormatAvailable(CF_TEXT))
1245     {
1246         if ((hMem = GetClipboardData(CF_TEXT)) != NULL)
1247         {
1248             str = (char_u *)GlobalLock(hMem);
1249
1250             /* The length is either what our metadata says or the strlen().
1251              * But limit it to the GlobalSize() for safety. */
1252             maxlen = (int)GlobalSize(hMem);
1253             if (metadata.txtlen >= 0)
1254             {
1255                 if (metadata.txtlen > maxlen)
1256                     str_size = maxlen;
1257                 else
1258                     str_size = metadata.txtlen;
1259             }
1260             else
1261             {
1262                 for (str_size = 0; str_size < maxlen; ++str_size)
1263                     if (str[str_size] == NUL)
1264                         break;
1265             }
1266
1267 # if defined(FEAT_MBYTE) && defined(WIN3264)
1268             /* The text is in the active codepage.  Convert to 'encoding',
1269              * going through UTF-16. */
1270             acp_to_enc(str, str_size, &to_free, &maxlen);
1271             if (to_free != NULL)
1272             {
1273                 str_size = maxlen;
1274                 str = to_free;
1275             }
1276 # endif
1277         }
1278     }
1279 #ifdef FEAT_MBYTE
1280     }
1281 #endif
1282
1283     if (str != NULL && *str != NUL)
1284     {
1285         char_u *temp_clipboard;
1286
1287         /* If the type is not known detect it. */
1288         if (metadata.type == -1)
1289             metadata.type = MAUTO;
1290
1291         /* Translate <CR><NL> into <NL>. */
1292         temp_clipboard = crnl_to_nl(str, &str_size);
1293         if (temp_clipboard != NULL)
1294         {
1295             clip_yank_selection(metadata.type, temp_clipboard, str_size, cbd);
1296             vim_free(temp_clipboard);
1297         }
1298     }
1299
1300     /* unlock the global object */
1301     if (hMem != NULL)
1302         GlobalUnlock(hMem);
1303 #ifdef FEAT_MBYTE
1304     if (rawh != NULL)
1305         GlobalUnlock(rawh);
1306 #endif
1307     CloseClipboard();
1308 #if defined(FEAT_MBYTE) && defined(WIN3264)
1309     vim_free(to_free);
1310 #endif
1311 }
1312
1313 /*
1314  * Send the current selection to the clipboard.
1315  */
1316     void
1317 clip_mch_set_selection(VimClipboard *cbd)
1318 {
1319     char_u              *str = NULL;
1320     VimClipType_t       metadata;
1321     long_u              txtlen;
1322     HGLOBAL             hMemRaw = NULL;
1323     HGLOBAL             hMem = NULL;
1324     HGLOBAL             hMemVim = NULL;
1325 # if defined(FEAT_MBYTE) && defined(WIN3264)
1326     HGLOBAL             hMemW = NULL;
1327 # endif
1328
1329     /* If the '*' register isn't already filled in, fill it in now */
1330     cbd->owned = TRUE;
1331     clip_get_selection(cbd);
1332     cbd->owned = FALSE;
1333
1334     /* Get the text to be put on the clipboard, with CR-LF. */
1335     metadata.type = clip_convert_selection(&str, &txtlen, cbd);
1336     if (metadata.type < 0)
1337         return;
1338     metadata.txtlen = (int)txtlen;
1339     metadata.ucslen = 0;
1340     metadata.rawlen = 0;
1341
1342 #ifdef FEAT_MBYTE
1343     /* Always set the raw bytes: 'encoding', NUL and the text.  This is used
1344      * when copy/paste from/to Vim with the same 'encoding', so that illegal
1345      * bytes can also be copied and no conversion is needed. */
1346     {
1347         LPSTR lpszMemRaw;
1348
1349         metadata.rawlen = (int)(txtlen + STRLEN(p_enc) + 1);
1350         hMemRaw = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
1351                                                          metadata.rawlen + 1);
1352         lpszMemRaw = (LPSTR)GlobalLock(hMemRaw);
1353         if (lpszMemRaw != NULL)
1354         {
1355             STRCPY(lpszMemRaw, p_enc);
1356             memcpy(lpszMemRaw + STRLEN(p_enc) + 1, str, txtlen + 1);
1357             GlobalUnlock(hMemRaw);
1358         }
1359         else
1360             metadata.rawlen = 0;
1361     }
1362 #endif
1363
1364 # if defined(FEAT_MBYTE) && defined(WIN3264)
1365     {
1366         WCHAR           *out;
1367         int             len = metadata.txtlen;
1368
1369         /* Convert the text to UTF-16. This is put on the clipboard as
1370          * CF_UNICODETEXT. */
1371         out = (WCHAR *)enc_to_utf16(str, &len);
1372         if (out != NULL)
1373         {
1374             WCHAR *lpszMemW;
1375
1376             /* Convert the text for CF_TEXT to Active codepage. Otherwise it's
1377              * p_enc, which has no relation to the Active codepage. */
1378             metadata.txtlen = WideCharToMultiByte(GetACP(), 0, out, len,
1379                                                                NULL, 0, 0, 0);
1380             vim_free(str);
1381             str = (char_u *)alloc((unsigned)(metadata.txtlen == 0 ? 1
1382                                                           : metadata.txtlen));
1383             if (str == NULL)
1384             {
1385                 vim_free(out);
1386                 return;         /* out of memory */
1387             }
1388             WideCharToMultiByte(GetACP(), 0, out, len,
1389                                                   str, metadata.txtlen, 0, 0);
1390
1391             /* Allocate memory for the UTF-16 text, add one NUL word to
1392              * terminate the string. */
1393             hMemW = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
1394                                                    (len + 1) * sizeof(WCHAR));
1395             lpszMemW = (WCHAR *)GlobalLock(hMemW);
1396             if (lpszMemW != NULL)
1397             {
1398                 memcpy(lpszMemW, out, len * sizeof(WCHAR));
1399                 lpszMemW[len] = NUL;
1400                 GlobalUnlock(hMemW);
1401             }
1402             vim_free(out);
1403             metadata.ucslen = len;
1404         }
1405     }
1406 # endif
1407
1408     /* Allocate memory for the text, add one NUL byte to terminate the string.
1409      */
1410     hMem = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, metadata.txtlen + 1);
1411     {
1412         LPSTR lpszMem = (LPSTR)GlobalLock(hMem);
1413
1414         if (lpszMem)
1415         {
1416             vim_strncpy(lpszMem, str, metadata.txtlen);
1417             GlobalUnlock(hMem);
1418         }
1419     }
1420
1421     /* Set up metadata: */
1422     {
1423         VimClipType_t *lpszMemVim = NULL;
1424
1425         hMemVim = GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE,
1426                                                        sizeof(VimClipType_t));
1427         lpszMemVim = (VimClipType_t *)GlobalLock(hMemVim);
1428         memcpy(lpszMemVim, &metadata, sizeof(metadata));
1429         GlobalUnlock(hMemVim);
1430     }
1431
1432     /*
1433      * Open the clipboard, clear it and put our text on it.
1434      * Always set our Vim format.  Put Unicode and plain text on it.
1435      *
1436      * Don't pass GetActiveWindow() as an argument to OpenClipboard()
1437      * because then we can't paste back into the same window for some
1438      * reason - webb.
1439      */
1440     if (vim_open_clipboard())
1441     {
1442         if (EmptyClipboard())
1443         {
1444             SetClipboardData(cbd->format, hMemVim);
1445             hMemVim = 0;
1446 # if defined(FEAT_MBYTE) && defined(WIN3264)
1447             if (hMemW != NULL)
1448             {
1449                 if (SetClipboardData(CF_UNICODETEXT, hMemW) != NULL)
1450                     hMemW = NULL;
1451             }
1452 # endif
1453             /* Always use CF_TEXT.  On Win98 Notepad won't obtain the
1454              * CF_UNICODETEXT text, only CF_TEXT. */
1455             SetClipboardData(CF_TEXT, hMem);
1456             hMem = 0;
1457         }
1458         CloseClipboard();
1459     }
1460
1461     vim_free(str);
1462     /* Free any allocations we didn't give to the clipboard: */
1463     if (hMemRaw)
1464         GlobalFree(hMemRaw);
1465     if (hMem)
1466         GlobalFree(hMem);
1467 # if defined(FEAT_MBYTE) && defined(WIN3264)
1468     if (hMemW)
1469         GlobalFree(hMemW);
1470 # endif
1471     if (hMemVim)
1472         GlobalFree(hMemVim);
1473 }
1474
1475 #endif /* FEAT_CLIPBOARD */
1476
1477 #if defined(FEAT_MBYTE) || defined(PROTO)
1478 /*
1479  * Note: the following two functions are only guaranteed to work when using
1480  * valid MS-Windows codepages or when iconv() is available.
1481  */
1482
1483 /*
1484  * Convert "str" from 'encoding' to UTF-16.
1485  * Input in "str" with length "*lenp".  When "lenp" is NULL, use strlen().
1486  * Output is returned as an allocated string.  "*lenp" is set to the length of
1487  * the result.  A trailing NUL is always added.
1488  * Returns NULL when out of memory.
1489  */
1490     short_u *
1491 enc_to_utf16(char_u *str, int *lenp)
1492 {
1493     vimconv_T   conv;
1494     WCHAR       *ret;
1495     char_u      *allocbuf = NULL;
1496     int         len_loc;
1497     int         length;
1498
1499     if (lenp == NULL)
1500     {
1501         len_loc = (int)STRLEN(str) + 1;
1502         lenp = &len_loc;
1503     }
1504
1505     if (enc_codepage > 0)
1506     {
1507         /* We can do any CP### -> UTF-16 in one pass, and we can do it
1508          * without iconv() (convert_* may need iconv). */
1509         MultiByteToWideChar_alloc(enc_codepage, 0, str, *lenp, &ret, &length);
1510     }
1511     else
1512     {
1513         /* Use "latin1" by default, we might be called before we have p_enc
1514          * set up.  Convert to utf-8 first, works better with iconv().  Does
1515          * nothing if 'encoding' is "utf-8". */
1516         conv.vc_type = CONV_NONE;
1517         if (convert_setup(&conv, p_enc ? p_enc : (char_u *)"latin1",
1518                                                    (char_u *)"utf-8") == FAIL)
1519             return NULL;
1520         if (conv.vc_type != CONV_NONE)
1521         {
1522             str = allocbuf = string_convert(&conv, str, lenp);
1523             if (str == NULL)
1524                 return NULL;
1525         }
1526         convert_setup(&conv, NULL, NULL);
1527
1528         length = utf8_to_utf16(str, *lenp, NULL, NULL);
1529         ret = (WCHAR *)alloc((unsigned)((length + 1) * sizeof(WCHAR)));
1530         if (ret != NULL)
1531         {
1532             utf8_to_utf16(str, *lenp, (short_u *)ret, NULL);
1533             ret[length] = 0;
1534         }
1535
1536         vim_free(allocbuf);
1537     }
1538
1539     *lenp = length;
1540     return (short_u *)ret;
1541 }
1542
1543 /*
1544  * Convert an UTF-16 string to 'encoding'.
1545  * Input in "str" with length (counted in wide characters) "*lenp".  When
1546  * "lenp" is NULL, use wcslen().
1547  * Output is returned as an allocated string.  If "*lenp" is not NULL it is
1548  * set to the length of the result.
1549  * Returns NULL when out of memory.
1550  */
1551     char_u *
1552 utf16_to_enc(short_u *str, int *lenp)
1553 {
1554     vimconv_T   conv;
1555     char_u      *utf8_str = NULL, *enc_str = NULL;
1556     int         len_loc;
1557
1558     if (lenp == NULL)
1559     {
1560         len_loc = (int)wcslen(str) + 1;
1561         lenp = &len_loc;
1562     }
1563
1564     if (enc_codepage > 0)
1565     {
1566         /* We can do any UTF-16 -> CP### in one pass. */
1567         int length;
1568
1569         WideCharToMultiByte_alloc(enc_codepage, 0, str, *lenp,
1570                                             (LPSTR *)&enc_str, &length, 0, 0);
1571         *lenp = length;
1572         return enc_str;
1573     }
1574
1575     /* Avoid allocating zero bytes, it generates an error message. */
1576     utf8_str = alloc(utf16_to_utf8(str, *lenp == 0 ? 1 : *lenp, NULL));
1577     if (utf8_str != NULL)
1578     {
1579         *lenp = utf16_to_utf8(str, *lenp, utf8_str);
1580
1581         /* We might be called before we have p_enc set up. */
1582         conv.vc_type = CONV_NONE;
1583         convert_setup(&conv, (char_u *)"utf-8",
1584                                             p_enc? p_enc: (char_u *)"latin1");
1585         if (conv.vc_type == CONV_NONE)
1586         {
1587             /* p_enc is utf-8, so we're done. */
1588             enc_str = utf8_str;
1589         }
1590         else
1591         {
1592             enc_str = string_convert(&conv, utf8_str, lenp);
1593             vim_free(utf8_str);
1594         }
1595
1596         convert_setup(&conv, NULL, NULL);
1597     }
1598
1599     return enc_str;
1600 }
1601 #endif /* FEAT_MBYTE */
1602
1603 #if (defined(FEAT_MBYTE) && defined(WIN3264)) || defined(PROTO)
1604 /*
1605  * Convert from the active codepage to 'encoding'.
1606  * Input is "str[str_size]".
1607  * The result is in allocated memory: "out[outlen]".  With terminating NUL.
1608  */
1609     void
1610 acp_to_enc(str, str_size, out, outlen)
1611     char_u      *str;
1612     int         str_size;
1613     char_u      **out;
1614     int         *outlen;
1615
1616 {
1617     LPWSTR      widestr;
1618
1619     MultiByteToWideChar_alloc(GetACP(), 0, str, str_size, &widestr, outlen);
1620     if (widestr != NULL)
1621     {
1622         ++*outlen;      /* Include the 0 after the string */
1623         *out = utf16_to_enc((short_u *)widestr, outlen);
1624         vim_free(widestr);
1625     }
1626 }
1627 #endif
1628
1629
1630 /*
1631  * Debugging helper: expose the MCH_WRITE_DUMP stuff to other modules
1632  */
1633 /*ARGSUSED*/
1634     void
1635 DumpPutS(
1636     const char *psz)
1637 {
1638 # ifdef MCH_WRITE_DUMP
1639     if (fdDump)
1640     {
1641         fputs(psz, fdDump);
1642         if (psz[strlen(psz) - 1] != '\n')
1643             fputc('\n', fdDump);
1644         fflush(fdDump);
1645     }
1646 # endif
1647 }
1648
1649 #ifdef _DEBUG
1650
1651 void __cdecl
1652 Trace(
1653     char *pszFormat,
1654     ...)
1655 {
1656     CHAR szBuff[2048];
1657     va_list args;
1658
1659     va_start(args, pszFormat);
1660     vsprintf(szBuff, pszFormat, args);
1661     va_end(args);
1662
1663     OutputDebugString(szBuff);
1664 }
1665
1666 #endif //_DEBUG
1667
1668 #if !defined(FEAT_GUI) || defined(PROTO)
1669 # if defined(FEAT_TITLE) && defined(WIN3264)
1670 extern HWND g_hWnd;     /* This is in os_win32.c. */
1671 # endif
1672
1673 /*
1674  * Showing the printer dialog is tricky since we have no GUI
1675  * window to parent it. The following routines are needed to
1676  * get the window parenting and Z-order to work properly.
1677  */
1678     static void
1679 GetConsoleHwnd(void)
1680 {
1681 # define MY_BUFSIZE 1024 // Buffer size for console window titles.
1682
1683     char pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated WindowTitle.
1684     char pszOldWindowTitle[MY_BUFSIZE]; // Contains original WindowTitle.
1685
1686     /* Skip if it's already set. */
1687     if (s_hwnd != 0)
1688         return;
1689
1690 # if defined(FEAT_TITLE) && defined(WIN3264)
1691     /* Window handle may have been found by init code (Windows NT only) */
1692     if (g_hWnd != 0)
1693     {
1694         s_hwnd = g_hWnd;
1695         return;
1696     }
1697 # endif
1698
1699     GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);
1700
1701     wsprintf(pszNewWindowTitle, "%s/%d/%d",
1702             pszOldWindowTitle,
1703             GetTickCount(),
1704             GetCurrentProcessId());
1705     SetConsoleTitle(pszNewWindowTitle);
1706     Sleep(40);
1707     s_hwnd = FindWindow(NULL, pszNewWindowTitle);
1708
1709     SetConsoleTitle(pszOldWindowTitle);
1710 }
1711
1712 /*
1713  * Console implementation of ":winpos".
1714  */
1715     int
1716 mch_get_winpos(int *x, int *y)
1717 {
1718     RECT  rect;
1719
1720     GetConsoleHwnd();
1721     GetWindowRect(s_hwnd, &rect);
1722     *x = rect.left;
1723     *y = rect.top;
1724     return OK;
1725 }
1726
1727 /*
1728  * Console implementation of ":winpos x y".
1729  */
1730     void
1731 mch_set_winpos(int x, int y)
1732 {
1733     GetConsoleHwnd();
1734     SetWindowPos(s_hwnd, NULL, x, y, 0, 0,
1735                  SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
1736 }
1737 #endif
1738
1739 #if (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) || defined(PROTO)
1740
1741 # ifdef WIN16
1742 #  define TEXT(a) a
1743 # endif
1744 /*=================================================================
1745  * Win32 printer stuff
1746  */
1747
1748 static HFONT            prt_font_handles[2][2][2];
1749 static PRINTDLG         prt_dlg;
1750 static const int        boldface[2] = {FW_REGULAR, FW_BOLD};
1751 static TEXTMETRIC       prt_tm;
1752 static int              prt_line_height;
1753 static int              prt_number_width;
1754 static int              prt_left_margin;
1755 static int              prt_right_margin;
1756 static int              prt_top_margin;
1757 static char_u           szAppName[] = TEXT("VIM");
1758 static HWND             hDlgPrint;
1759 static int              *bUserAbort = NULL;
1760 static char_u           *prt_name = NULL;
1761
1762 /* Defines which are also in vim.rc. */
1763 #define IDC_BOX1                400
1764 #define IDC_PRINTTEXT1          401
1765 #define IDC_PRINTTEXT2          402
1766 #define IDC_PROGRESS            403
1767
1768 /*
1769  * Convert BGR to RGB for Windows GDI calls
1770  */
1771     static COLORREF
1772 swap_me(COLORREF colorref)
1773 {
1774     int  temp;
1775     char *ptr = (char *)&colorref;
1776
1777     temp = *(ptr);
1778     *(ptr ) = *(ptr + 2);
1779     *(ptr + 2) = temp;
1780     return colorref;
1781 }
1782
1783 /* Attempt to make this work for old and new compilers */
1784 #if !defined(_WIN64) && (!defined(_MSC_VER) || _MSC_VER < 1300)
1785 # define PDP_RETVAL BOOL
1786 #else
1787 # define PDP_RETVAL INT_PTR
1788 #endif
1789
1790 /*ARGSUSED*/
1791     static PDP_RETVAL CALLBACK
1792 PrintDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
1793 {
1794 #ifdef FEAT_GETTEXT
1795     NONCLIENTMETRICS nm;
1796     static HFONT hfont;
1797 #endif
1798
1799     switch (message)
1800     {
1801         case WM_INITDIALOG:
1802 #ifdef FEAT_GETTEXT
1803             nm.cbSize = sizeof(NONCLIENTMETRICS);
1804             if (SystemParametersInfo(
1805                         SPI_GETNONCLIENTMETRICS,
1806                         sizeof(NONCLIENTMETRICS),
1807                         &nm,
1808                         0))
1809             {
1810                 char buff[MAX_PATH];
1811                 int i;
1812
1813                 /* Translate the dialog texts */
1814                 hfont = CreateFontIndirect(&nm.lfMessageFont);
1815                 for (i = IDC_PRINTTEXT1; i <= IDC_PROGRESS; i++)
1816                 {
1817                     SendDlgItemMessage(hDlg, i, WM_SETFONT, (WPARAM)hfont, 1);
1818                     if (GetDlgItemText(hDlg,i, buff, sizeof(buff)))
1819                         SetDlgItemText(hDlg,i, _(buff));
1820                 }
1821                 SendDlgItemMessage(hDlg, IDCANCEL,
1822                                                 WM_SETFONT, (WPARAM)hfont, 1);
1823                 if (GetDlgItemText(hDlg,IDCANCEL, buff, sizeof(buff)))
1824                     SetDlgItemText(hDlg,IDCANCEL, _(buff));
1825             }
1826 #endif
1827             SetWindowText(hDlg, szAppName);
1828             if (prt_name != NULL)
1829             {
1830                 SetDlgItemText(hDlg, IDC_PRINTTEXT2, (LPSTR)prt_name);
1831                 vim_free(prt_name);
1832                 prt_name = NULL;
1833             }
1834             EnableMenuItem(GetSystemMenu(hDlg, FALSE), SC_CLOSE, MF_GRAYED);
1835 #ifndef FEAT_GUI
1836             BringWindowToTop(s_hwnd);
1837 #endif
1838             return TRUE;
1839
1840         case WM_COMMAND:
1841             *bUserAbort = TRUE;
1842             EnableWindow(GetParent(hDlg), TRUE);
1843             DestroyWindow(hDlg);
1844             hDlgPrint = NULL;
1845 #ifdef FEAT_GETTEXT
1846             DeleteObject(hfont);
1847 #endif
1848             return TRUE;
1849     }
1850     return FALSE;
1851 }
1852
1853 /*ARGSUSED*/
1854     static BOOL CALLBACK
1855 AbortProc(HDC hdcPrn, int iCode)
1856 {
1857     MSG msg;
1858
1859     while (!*bUserAbort && pPeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
1860     {
1861         if (!hDlgPrint || !pIsDialogMessage(hDlgPrint, &msg))
1862         {
1863             TranslateMessage(&msg);
1864             pDispatchMessage(&msg);
1865         }
1866     }
1867     return !*bUserAbort;
1868 }
1869
1870 #ifndef FEAT_GUI
1871
1872     static UINT_PTR CALLBACK
1873 PrintHookProc(
1874         HWND hDlg,      // handle to dialog box
1875         UINT uiMsg,     // message identifier
1876         WPARAM wParam,  // message parameter
1877         LPARAM lParam   // message parameter
1878         )
1879 {
1880     HWND        hwndOwner;
1881     RECT        rc, rcDlg, rcOwner;
1882     PRINTDLG    *pPD;
1883
1884     if (uiMsg == WM_INITDIALOG)
1885     {
1886         // Get the owner window and dialog box rectangles.
1887         if ((hwndOwner = GetParent(hDlg)) == NULL)
1888             hwndOwner = GetDesktopWindow();
1889
1890         GetWindowRect(hwndOwner, &rcOwner);
1891         GetWindowRect(hDlg, &rcDlg);
1892         CopyRect(&rc, &rcOwner);
1893
1894         // Offset the owner and dialog box rectangles so that
1895         // right and bottom values represent the width and
1896         // height, and then offset the owner again to discard
1897         // space taken up by the dialog box.
1898
1899         OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
1900         OffsetRect(&rc, -rc.left, -rc.top);
1901         OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);
1902
1903         // The new position is the sum of half the remaining
1904         // space and the owner's original position.
1905
1906         SetWindowPos(hDlg,
1907                 HWND_TOP,
1908                 rcOwner.left + (rc.right / 2),
1909                 rcOwner.top + (rc.bottom / 2),
1910                 0, 0,           // ignores size arguments
1911                 SWP_NOSIZE);
1912
1913         /*  tackle the printdlg copiesctrl problem */
1914         pPD = (PRINTDLG *)lParam;
1915         pPD->nCopies = (WORD)pPD->lCustData;
1916         SetDlgItemInt( hDlg, edt3, pPD->nCopies, FALSE );
1917         /*  Bring the window to top */
1918         BringWindowToTop(GetParent(hDlg));
1919         SetForegroundWindow(hDlg);
1920     }
1921
1922     return FALSE;
1923 }
1924 #endif
1925
1926     void
1927 mch_print_cleanup(void)
1928 {
1929     int pifItalic;
1930     int pifBold;
1931     int pifUnderline;
1932
1933     for (pifBold = 0; pifBold <= 1; pifBold++)
1934         for (pifItalic = 0; pifItalic <= 1; pifItalic++)
1935             for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
1936                 DeleteObject(prt_font_handles[pifBold][pifItalic][pifUnderline]);
1937
1938     if (prt_dlg.hDC != NULL)
1939         DeleteDC(prt_dlg.hDC);
1940     if (!*bUserAbort)
1941         SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
1942 }
1943
1944     static int
1945 to_device_units(int idx, int dpi, int physsize, int offset, int def_number)
1946 {
1947     int         ret = 0;
1948     int         u;
1949     int         nr;
1950
1951     u = prt_get_unit(idx);
1952     if (u == PRT_UNIT_NONE)
1953     {
1954         u = PRT_UNIT_PERC;
1955         nr = def_number;
1956     }
1957     else
1958         nr = printer_opts[idx].number;
1959
1960     switch (u)
1961     {
1962         case PRT_UNIT_PERC:
1963             ret = (physsize * nr) / 100;
1964             break;
1965         case PRT_UNIT_INCH:
1966             ret = (nr * dpi);
1967             break;
1968         case PRT_UNIT_MM:
1969             ret = (nr * 10 * dpi) / 254;
1970             break;
1971         case PRT_UNIT_POINT:
1972             ret = (nr * 10 * dpi) / 720;
1973             break;
1974     }
1975
1976     if (ret < offset)
1977         return 0;
1978     else
1979         return ret - offset;
1980 }
1981
1982     static int
1983 prt_get_cpl(void)
1984 {
1985     int         hr;
1986     int         phyw;
1987     int         dvoff;
1988     int         rev_offset;
1989     int         dpi;
1990 #ifdef WIN16
1991     POINT       pagesize;
1992 #endif
1993
1994     GetTextMetrics(prt_dlg.hDC, &prt_tm);
1995     prt_line_height = prt_tm.tmHeight + prt_tm.tmExternalLeading;
1996
1997     hr      = GetDeviceCaps(prt_dlg.hDC, HORZRES);
1998 #ifdef WIN16
1999     Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
2000     phyw    = pagesize.x;
2001     Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
2002     dvoff   = pagesize.x;
2003 #else
2004     phyw    = GetDeviceCaps(prt_dlg.hDC, PHYSICALWIDTH);
2005     dvoff   = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETX);
2006 #endif
2007     dpi     = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSX);
2008
2009     rev_offset = phyw - (dvoff + hr);
2010
2011     prt_left_margin = to_device_units(OPT_PRINT_LEFT, dpi, phyw, dvoff, 10);
2012     if (prt_use_number())
2013     {
2014         prt_number_width = PRINT_NUMBER_WIDTH * prt_tm.tmAveCharWidth;
2015         prt_left_margin += prt_number_width;
2016     }
2017     else
2018         prt_number_width = 0;
2019
2020     prt_right_margin = hr - to_device_units(OPT_PRINT_RIGHT, dpi, phyw,
2021                                                                rev_offset, 5);
2022
2023     return (prt_right_margin - prt_left_margin) / prt_tm.tmAveCharWidth;
2024 }
2025
2026     static int
2027 prt_get_lpp(void)
2028 {
2029     int vr;
2030     int phyw;
2031     int dvoff;
2032     int rev_offset;
2033     int bottom_margin;
2034     int dpi;
2035 #ifdef WIN16
2036     POINT pagesize;
2037 #endif
2038
2039     vr      = GetDeviceCaps(prt_dlg.hDC, VERTRES);
2040 #ifdef WIN16
2041     Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
2042     phyw    = pagesize.y;
2043     Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
2044     dvoff   = pagesize.y;
2045 #else
2046     phyw    = GetDeviceCaps(prt_dlg.hDC, PHYSICALHEIGHT);
2047     dvoff   = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETY);
2048 #endif
2049     dpi     = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSY);
2050
2051     rev_offset = phyw - (dvoff + vr);
2052
2053     prt_top_margin = to_device_units(OPT_PRINT_TOP, dpi, phyw, dvoff, 5);
2054
2055     /* adjust top margin if there is a header */
2056     prt_top_margin += prt_line_height * prt_header_height();
2057
2058     bottom_margin = vr - to_device_units(OPT_PRINT_BOT, dpi, phyw,
2059                                                                rev_offset, 5);
2060
2061     return (bottom_margin - prt_top_margin) / prt_line_height;
2062 }
2063
2064     int
2065 mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
2066 {
2067     static HGLOBAL      stored_dm = NULL;
2068     static HGLOBAL      stored_devn = NULL;
2069     static int          stored_nCopies = 1;
2070     static int          stored_nFlags = 0;
2071
2072     LOGFONT             fLogFont;
2073     int                 pifItalic;
2074     int                 pifBold;
2075     int                 pifUnderline;
2076
2077     DEVMODE             *mem;
2078     DEVNAMES            *devname;
2079     int                 i;
2080
2081     bUserAbort = &(psettings->user_abort);
2082     vim_memset(&prt_dlg, 0, sizeof(PRINTDLG));
2083     prt_dlg.lStructSize = sizeof(PRINTDLG);
2084 #ifndef FEAT_GUI
2085     GetConsoleHwnd();       /* get value of s_hwnd */
2086 #endif
2087     prt_dlg.hwndOwner = s_hwnd;
2088     prt_dlg.Flags = PD_NOPAGENUMS | PD_NOSELECTION | PD_RETURNDC;
2089     if (!forceit)
2090     {
2091         prt_dlg.hDevMode = stored_dm;
2092         prt_dlg.hDevNames = stored_devn;
2093         prt_dlg.lCustData = stored_nCopies; // work around bug in print dialog
2094 #ifndef FEAT_GUI
2095         /*
2096          * Use hook to prevent console window being sent to back
2097          */
2098         prt_dlg.lpfnPrintHook = PrintHookProc;
2099         prt_dlg.Flags |= PD_ENABLEPRINTHOOK;
2100 #endif
2101         prt_dlg.Flags |= stored_nFlags;
2102     }
2103
2104     /*
2105      * If bang present, return default printer setup with no dialog
2106      * never show dialog if we are running over telnet
2107      */
2108     if (forceit
2109 #ifndef FEAT_GUI
2110             || !term_console
2111 #endif
2112             )
2113     {
2114         prt_dlg.Flags |= PD_RETURNDEFAULT;
2115 #ifdef WIN3264
2116         /*
2117          * MSDN suggests setting the first parameter to WINSPOOL for
2118          * NT, but NULL appears to work just as well.
2119          */
2120         if (*p_pdev != NUL)
2121             prt_dlg.hDC = CreateDC(NULL, p_pdev, NULL, NULL);
2122         else
2123 #endif
2124         {
2125             prt_dlg.Flags |= PD_RETURNDEFAULT;
2126             if (PrintDlg(&prt_dlg) == 0)
2127                 goto init_fail_dlg;
2128         }
2129     }
2130     else if (PrintDlg(&prt_dlg) == 0)
2131         goto init_fail_dlg;
2132     else
2133     {
2134         /*
2135          * keep the previous driver context
2136          */
2137         stored_dm = prt_dlg.hDevMode;
2138         stored_devn = prt_dlg.hDevNames;
2139         stored_nFlags = prt_dlg.Flags;
2140         stored_nCopies = prt_dlg.nCopies;
2141     }
2142
2143     if (prt_dlg.hDC == NULL)
2144     {
2145         EMSG(_("E237: Printer selection failed"));
2146         mch_print_cleanup();
2147         return FALSE;
2148     }
2149
2150     /* Not all printer drivers report the support of color (or grey) in the
2151      * same way.  Let's set has_color if there appears to be some way to print
2152      * more than B&W. */
2153     i = GetDeviceCaps(prt_dlg.hDC, NUMCOLORS);
2154     psettings->has_color = (GetDeviceCaps(prt_dlg.hDC, BITSPIXEL) > 1
2155                                    || GetDeviceCaps(prt_dlg.hDC, PLANES) > 1
2156                                    || i > 2 || i == -1);
2157
2158     /* Ensure all font styles are baseline aligned */
2159     SetTextAlign(prt_dlg.hDC, TA_BASELINE|TA_LEFT);
2160
2161     /*
2162      * On some windows systems the nCopies parameter is not
2163      * passed back correctly. It must be retrieved from the
2164      * hDevMode struct.
2165      */
2166     mem = (DEVMODE *)GlobalLock(prt_dlg.hDevMode);
2167     if (mem != NULL)
2168     {
2169 #ifdef WIN3264
2170         if (mem->dmCopies != 1)
2171             stored_nCopies = mem->dmCopies;
2172 #endif
2173         if ((mem->dmFields & DM_DUPLEX) && (mem->dmDuplex & ~DMDUP_SIMPLEX))
2174             psettings->duplex = TRUE;
2175         if ((mem->dmFields & DM_COLOR) && (mem->dmColor & DMCOLOR_COLOR))
2176             psettings->has_color = TRUE;
2177     }
2178     GlobalUnlock(prt_dlg.hDevMode);
2179
2180     devname = (DEVNAMES *)GlobalLock(prt_dlg.hDevNames);
2181     if (devname != 0)
2182     {
2183         char_u  *printer_name = (char_u *)devname + devname->wDeviceOffset;
2184         char_u  *port_name = (char_u *)devname +devname->wOutputOffset;
2185         char_u  *text = _("to %s on %s");
2186
2187         prt_name = alloc((unsigned)(STRLEN(printer_name) + STRLEN(port_name)
2188                                                              + STRLEN(text)));
2189         if (prt_name != NULL)
2190             wsprintf(prt_name, text, printer_name, port_name);
2191     }
2192     GlobalUnlock(prt_dlg.hDevNames);
2193
2194     /*
2195      * Initialise the font according to 'printfont'
2196      */
2197     vim_memset(&fLogFont, 0, sizeof(fLogFont));
2198     if (get_logfont(&fLogFont, p_pfn, prt_dlg.hDC, TRUE) == FAIL)
2199     {
2200         EMSG2(_("E613: Unknown printer font: %s"), p_pfn);
2201         mch_print_cleanup();
2202         return FALSE;
2203     }
2204
2205     for (pifBold = 0; pifBold <= 1; pifBold++)
2206         for (pifItalic = 0; pifItalic <= 1; pifItalic++)
2207             for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
2208             {
2209                 fLogFont.lfWeight =  boldface[pifBold];
2210                 fLogFont.lfItalic = pifItalic;
2211                 fLogFont.lfUnderline = pifUnderline;
2212                 prt_font_handles[pifBold][pifItalic][pifUnderline]
2213                                               = CreateFontIndirect(&fLogFont);
2214             }
2215
2216     SetBkMode(prt_dlg.hDC, OPAQUE);
2217     SelectObject(prt_dlg.hDC, prt_font_handles[0][0][0]);
2218
2219     /*
2220      * Fill in the settings struct
2221      */
2222     psettings->chars_per_line = prt_get_cpl();
2223     psettings->lines_per_page = prt_get_lpp();
2224     psettings->n_collated_copies = (prt_dlg.Flags & PD_COLLATE)
2225                                                         ? prt_dlg.nCopies : 1;
2226     psettings->n_uncollated_copies = (prt_dlg.Flags & PD_COLLATE)
2227                                                         ? 1 : prt_dlg.nCopies;
2228
2229     if (psettings->n_collated_copies == 0)
2230         psettings->n_collated_copies = 1;
2231
2232     if (psettings->n_uncollated_copies == 0)
2233         psettings->n_uncollated_copies = 1;
2234
2235     psettings->jobname = jobname;
2236
2237     return TRUE;
2238
2239 init_fail_dlg:
2240     {
2241         DWORD err = CommDlgExtendedError();
2242
2243         if (err)
2244         {
2245 #ifdef WIN16
2246             char buf[20];
2247
2248             sprintf(buf, "%ld", err);
2249             EMSG2(_("E238: Print error: %s"), buf);
2250 #else
2251             char_u *buf;
2252
2253             /* I suspect FormatMessage() doesn't work for values returned by
2254              * CommDlgExtendedError().  What does? */
2255             FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2256                           FORMAT_MESSAGE_FROM_SYSTEM |
2257                           FORMAT_MESSAGE_IGNORE_INSERTS,
2258                           NULL, err, 0, (LPTSTR)(&buf), 0, NULL);
2259             EMSG2(_("E238: Print error: %s"),
2260                                   buf == NULL ? (char_u *)_("Unknown") : buf);
2261             LocalFree((LPVOID)(buf));
2262 #endif
2263         }
2264         else
2265             msg_clr_eos(); /* Maybe canceled */
2266
2267         mch_print_cleanup();
2268         return FALSE;
2269     }
2270 }
2271
2272
2273     int
2274 mch_print_begin(prt_settings_T *psettings)
2275 {
2276     int                 ret;
2277     static DOCINFO      di;
2278     char                szBuffer[300];
2279
2280     hDlgPrint = CreateDialog(GetModuleHandle(NULL), TEXT("PrintDlgBox"),
2281                                              prt_dlg.hwndOwner, PrintDlgProc);
2282 #ifdef WIN16
2283     Escape(prt_dlg.hDC, SETABORTPROC, 0, (LPSTR)AbortProc, NULL);
2284 #else
2285     SetAbortProc(prt_dlg.hDC, AbortProc);
2286 #endif
2287     wsprintf(szBuffer, _("Printing '%s'"), gettail(psettings->jobname));
2288     SetDlgItemText(hDlgPrint, IDC_PRINTTEXT1, (LPSTR)szBuffer);
2289
2290     vim_memset(&di, 0, sizeof(DOCINFO));
2291     di.cbSize = sizeof(DOCINFO);
2292     di.lpszDocName = psettings->jobname;
2293     ret = StartDoc(prt_dlg.hDC, &di);
2294
2295 #ifdef FEAT_GUI
2296     /* Give focus back to main window (when using MDI). */
2297     SetFocus(s_hwnd);
2298 #endif
2299
2300     return (ret > 0);
2301 }
2302
2303 /*ARGSUSED*/
2304     void
2305 mch_print_end(prt_settings_T *psettings)
2306 {
2307     EndDoc(prt_dlg.hDC);
2308     if (!*bUserAbort)
2309         SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
2310 }
2311
2312     int
2313 mch_print_end_page(void)
2314 {
2315     return (EndPage(prt_dlg.hDC) > 0);
2316 }
2317
2318     int
2319 mch_print_begin_page(char_u *msg)
2320 {
2321     if (msg != NULL)
2322         SetDlgItemText(hDlgPrint, IDC_PROGRESS, (LPSTR)msg);
2323     return (StartPage(prt_dlg.hDC) > 0);
2324 }
2325
2326     int
2327 mch_print_blank_page(void)
2328 {
2329     return (mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE);
2330 }
2331
2332 static int prt_pos_x = 0;
2333 static int prt_pos_y = 0;
2334
2335     void
2336 mch_print_start_line(margin, page_line)
2337     int         margin;
2338     int         page_line;
2339 {
2340     if (margin)
2341         prt_pos_x = -prt_number_width;
2342     else
2343         prt_pos_x = 0;
2344     prt_pos_y = page_line * prt_line_height
2345                                  + prt_tm.tmAscent + prt_tm.tmExternalLeading;
2346 }
2347
2348     int
2349 mch_print_text_out(char_u *p, int len)
2350 {
2351 #ifdef FEAT_PROPORTIONAL_FONTS
2352     SIZE        sz;
2353 #endif
2354
2355     TextOut(prt_dlg.hDC, prt_pos_x + prt_left_margin,
2356                                           prt_pos_y + prt_top_margin, p, len);
2357 #ifndef FEAT_PROPORTIONAL_FONTS
2358     prt_pos_x += len * prt_tm.tmAveCharWidth;
2359     return (prt_pos_x + prt_left_margin + prt_tm.tmAveCharWidth
2360                                      + prt_tm.tmOverhang > prt_right_margin);
2361 #else
2362 # ifdef WIN16
2363     GetTextExtentPoint(prt_dlg.hDC, p, len, &sz);
2364 # else
2365     GetTextExtentPoint32(prt_dlg.hDC, p, len, &sz);
2366 # endif
2367     prt_pos_x += (sz.cx - prt_tm.tmOverhang);
2368     /* This is wrong when printing spaces for a TAB. */
2369     if (p[len] == NUL)
2370         return FALSE;
2371 # ifdef WIN16
2372     GetTextExtentPoint(prt_dlg.hDC, p + len, 1, &sz);
2373 # else
2374     GetTextExtentPoint32(prt_dlg.hDC, p + len, 1, &sz);
2375 # endif
2376     return (prt_pos_x + prt_left_margin + sz.cx > prt_right_margin);
2377 #endif
2378 }
2379
2380     void
2381 mch_print_set_font(int iBold, int iItalic, int iUnderline)
2382 {
2383     SelectObject(prt_dlg.hDC, prt_font_handles[iBold][iItalic][iUnderline]);
2384 }
2385
2386     void
2387 mch_print_set_bg(long_u bgcol)
2388 {
2389     SetBkColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC,
2390                                                    swap_me((COLORREF)bgcol)));
2391     /*
2392      * With a white background we can draw characters transparent, which is
2393      * good for italic characters that overlap to the next char cell.
2394      */
2395     if (bgcol == 0xffffffUL)
2396         SetBkMode(prt_dlg.hDC, TRANSPARENT);
2397     else
2398         SetBkMode(prt_dlg.hDC, OPAQUE);
2399 }
2400
2401     void
2402 mch_print_set_fg(long_u fgcol)
2403 {
2404     SetTextColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC,
2405                                                    swap_me((COLORREF)fgcol)));
2406 }
2407
2408 #endif /*FEAT_PRINTER && !FEAT_POSTSCRIPT*/
2409
2410
2411
2412 #if defined(FEAT_SHORTCUT) || defined(PROTO)
2413 # include <shlobj.h>
2414
2415 /*
2416  * When "fname" is the name of a shortcut (*.lnk) resolve the file it points
2417  * to and return that name in allocated memory.
2418  * Otherwise NULL is returned.
2419  */
2420     char_u *
2421 mch_resolve_shortcut(char_u *fname)
2422 {
2423     HRESULT             hr;
2424     IShellLink          *psl = NULL;
2425     IPersistFile        *ppf = NULL;
2426     OLECHAR             wsz[MAX_PATH];
2427     WIN32_FIND_DATA     ffd; // we get those free of charge
2428     TCHAR               buf[MAX_PATH]; // could have simply reused 'wsz'...
2429     char_u              *rfname = NULL;
2430     int                 len;
2431
2432     /* Check if the file name ends in ".lnk". Avoid calling
2433      * CoCreateInstance(), it's quite slow. */
2434     if (fname == NULL)
2435         return rfname;
2436     len = (int)STRLEN(fname);
2437     if (len <= 4 || STRNICMP(fname + len - 4, ".lnk", 4) != 0)
2438         return rfname;
2439
2440     CoInitialize(NULL);
2441
2442     // create a link manager object and request its interface
2443     hr = CoCreateInstance(
2444             &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2445             &IID_IShellLink, (void**)&psl);
2446     if (hr != S_OK)
2447         goto shortcut_error;
2448
2449     // Get a pointer to the IPersistFile interface.
2450     hr = psl->lpVtbl->QueryInterface(
2451             psl, &IID_IPersistFile, (void**)&ppf);
2452     if (hr != S_OK)
2453         goto shortcut_error;
2454
2455     // full path string must be in Unicode.
2456     MultiByteToWideChar(CP_ACP, 0, fname, -1, wsz, MAX_PATH);
2457
2458     // "load" the name and resolve the link
2459     hr = ppf->lpVtbl->Load(ppf, wsz, STGM_READ);
2460     if (hr != S_OK)
2461         goto shortcut_error;
2462 #if 0  // This makes Vim wait a long time if the target doesn't exist.
2463     hr = psl->lpVtbl->Resolve(psl, NULL, SLR_NO_UI);
2464     if (hr != S_OK)
2465         goto shortcut_error;
2466 #endif
2467
2468     // Get the path to the link target.
2469     ZeroMemory(buf, MAX_PATH);
2470     hr = psl->lpVtbl->GetPath(psl, buf, MAX_PATH, &ffd, 0);
2471     if (hr == S_OK && buf[0] != NUL)
2472         rfname = vim_strsave(buf);
2473
2474 shortcut_error:
2475     // Release all interface pointers (both belong to the same object)
2476     if (ppf != NULL)
2477         ppf->lpVtbl->Release(ppf);
2478     if (psl != NULL)
2479         psl->lpVtbl->Release(psl);
2480
2481     CoUninitialize();
2482     return rfname;
2483 }
2484 #endif
2485
2486 #if (defined(FEAT_EVAL) && !defined(FEAT_GUI)) || defined(PROTO)
2487 /*
2488  * Bring ourselves to the foreground.  Does work if the OS doesn't allow it.
2489  */
2490     void
2491 win32_set_foreground()
2492 {
2493 # ifndef FEAT_GUI
2494     GetConsoleHwnd();       /* get value of s_hwnd */
2495 # endif
2496     if (s_hwnd != 0)
2497         SetForegroundWindow(s_hwnd);
2498 }
2499 #endif
2500
2501 #if defined(FEAT_CLIENTSERVER) || defined(PROTO)
2502 /*
2503  * Client-server code for Vim
2504  *
2505  * Originally written by Paul Moore
2506  */
2507
2508 /* In order to handle inter-process messages, we need to have a window. But
2509  * the functions in this module can be called before the main GUI window is
2510  * created (and may also be called in the console version, where there is no
2511  * GUI window at all).
2512  *
2513  * So we create a hidden window, and arrange to destroy it on exit.
2514  */
2515 HWND message_window = 0;            /* window that's handling messsages */
2516
2517 #define VIM_CLASSNAME      "VIM_MESSAGES"
2518 #define VIM_CLASSNAME_LEN  (sizeof(VIM_CLASSNAME) - 1)
2519
2520 /* Communication is via WM_COPYDATA messages. The message type is send in
2521  * the dwData parameter. Types are defined here. */
2522 #define COPYDATA_KEYS           0
2523 #define COPYDATA_REPLY          1
2524 #define COPYDATA_EXPR           10
2525 #define COPYDATA_RESULT         11
2526 #define COPYDATA_ERROR_RESULT   12
2527 #define COPYDATA_ENCODING       20
2528
2529 /* This is a structure containing a server HWND and its name. */
2530 struct server_id
2531 {
2532     HWND hwnd;
2533     char_u *name;
2534 };
2535
2536 /* Last received 'encoding' that the client uses. */
2537 static char_u   *client_enc = NULL;
2538
2539 /*
2540  * Tell the other side what encoding we are using.
2541  * Errors are ignored.
2542  */
2543     static void
2544 serverSendEnc(HWND target)
2545 {
2546     COPYDATASTRUCT data;
2547
2548     data.dwData = COPYDATA_ENCODING;
2549 #ifdef FEAT_MBYTE
2550     data.cbData = (DWORD)STRLEN(p_enc) + 1;
2551     data.lpData = p_enc;
2552 #else
2553     data.cbData = (DWORD)STRLEN("latin1") + 1;
2554     data.lpData = "latin1";
2555 #endif
2556     (void)SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2557                                                              (LPARAM)(&data));
2558 }
2559
2560 /*
2561  * Clean up on exit. This destroys the hidden message window.
2562  */
2563     static void
2564 #ifdef __BORLANDC__
2565     _RTLENTRYF
2566 #endif
2567 CleanUpMessaging(void)
2568 {
2569     if (message_window != 0)
2570     {
2571         DestroyWindow(message_window);
2572         message_window = 0;
2573     }
2574 }
2575
2576 static int save_reply(HWND server, char_u *reply, int expr);
2577
2578 /*s
2579  * The window procedure for the hidden message window.
2580  * It handles callback messages and notifications from servers.
2581  * In order to process these messages, it is necessary to run a
2582  * message loop. Code which may run before the main message loop
2583  * is started (in the GUI) is careful to pump messages when it needs
2584  * to. Features which require message delivery during normal use will
2585  * not work in the console version - this basically means those
2586  * features which allow Vim to act as a server, rather than a client.
2587  */
2588     static LRESULT CALLBACK
2589 Messaging_WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2590 {
2591     if (msg == WM_COPYDATA)
2592     {
2593         /* This is a message from another Vim. The dwData member of the
2594          * COPYDATASTRUCT determines the type of message:
2595          *   COPYDATA_ENCODING:
2596          *      The encoding that the client uses. Following messages will
2597          *      use this encoding, convert if needed.
2598          *   COPYDATA_KEYS:
2599          *      A key sequence. We are a server, and a client wants these keys
2600          *      adding to the input queue.
2601          *   COPYDATA_REPLY:
2602          *      A reply. We are a client, and a server has sent this message
2603          *      in response to a request.  (server2client())
2604          *   COPYDATA_EXPR:
2605          *      An expression. We are a server, and a client wants us to
2606          *      evaluate this expression.
2607          *   COPYDATA_RESULT:
2608          *      A reply. We are a client, and a server has sent this message
2609          *      in response to a COPYDATA_EXPR.
2610          *   COPYDATA_ERROR_RESULT:
2611          *      A reply. We are a client, and a server has sent this message
2612          *      in response to a COPYDATA_EXPR that failed to evaluate.
2613          */
2614         COPYDATASTRUCT  *data = (COPYDATASTRUCT*)lParam;
2615         HWND            sender = (HWND)wParam;
2616         COPYDATASTRUCT  reply;
2617         char_u          *res;
2618         char_u          winstr[30];
2619         int             retval;
2620         char_u          *str;
2621         char_u          *tofree;
2622
2623         switch (data->dwData)
2624         {
2625         case COPYDATA_ENCODING:
2626 # ifdef FEAT_MBYTE
2627             /* Remember the encoding that the client uses. */
2628             vim_free(client_enc);
2629             client_enc = enc_canonize((char_u *)data->lpData);
2630 # endif
2631             return 1;
2632
2633         case COPYDATA_KEYS:
2634             /* Remember who sent this, for <client> */
2635             clientWindow = sender;
2636
2637             /* Add the received keys to the input buffer.  The loop waiting
2638              * for the user to do something should check the input buffer. */
2639             str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2640             server_to_input_buf(str);
2641             vim_free(tofree);
2642
2643 # ifdef FEAT_GUI
2644             /* Wake up the main GUI loop. */
2645             if (s_hwnd != 0)
2646                 PostMessage(s_hwnd, WM_NULL, 0, 0);
2647 # endif
2648             return 1;
2649
2650         case COPYDATA_EXPR:
2651             /* Remember who sent this, for <client> */
2652             clientWindow = sender;
2653
2654             str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2655             res = eval_client_expr_to_string(str);
2656             vim_free(tofree);
2657
2658             if (res == NULL)
2659             {
2660                 res = vim_strsave(_(e_invexprmsg));
2661                 reply.dwData = COPYDATA_ERROR_RESULT;
2662             }
2663             else
2664                 reply.dwData = COPYDATA_RESULT;
2665             reply.lpData = res;
2666             reply.cbData = (DWORD)STRLEN(res) + 1;
2667
2668             serverSendEnc(sender);
2669             retval = (int)SendMessage(sender, WM_COPYDATA, (WPARAM)message_window,
2670                                                             (LPARAM)(&reply));
2671             vim_free(res);
2672             return retval;
2673
2674         case COPYDATA_REPLY:
2675         case COPYDATA_RESULT:
2676         case COPYDATA_ERROR_RESULT:
2677             if (data->lpData != NULL)
2678             {
2679                 str = serverConvert(client_enc, (char_u *)data->lpData,
2680                                                                      &tofree);
2681                 if (tofree == NULL)
2682                     str = vim_strsave(str);
2683                 if (save_reply(sender, str,
2684                            (data->dwData == COPYDATA_REPLY ?  0 :
2685                            (data->dwData == COPYDATA_RESULT ? 1 :
2686                                                               2))) == FAIL)
2687                     vim_free(str);
2688 #ifdef FEAT_AUTOCMD
2689                 else if (data->dwData == COPYDATA_REPLY)
2690                 {
2691                     sprintf((char *)winstr, PRINTF_HEX_LONG_U, (long_u)sender);
2692                     apply_autocmds(EVENT_REMOTEREPLY, winstr, str,
2693                                                                 TRUE, curbuf);
2694                 }
2695 #endif
2696             }
2697             return 1;
2698         }
2699
2700         return 0;
2701     }
2702
2703     else if (msg == WM_ACTIVATE && wParam == WA_ACTIVE)
2704     {
2705         /* When the message window is activated (brought to the foreground),
2706          * this actually applies to the text window. */
2707 #ifndef FEAT_GUI
2708         GetConsoleHwnd();           /* get value of s_hwnd */
2709 #endif
2710         if (s_hwnd != 0)
2711         {
2712             SetForegroundWindow(s_hwnd);
2713             return 0;
2714         }
2715     }
2716
2717     return DefWindowProc(hwnd, msg, wParam, lParam);
2718 }
2719
2720 /*
2721  * Initialise the message handling process.  This involves creating a window
2722  * to handle messages - the window will not be visible.
2723  */
2724     void
2725 serverInitMessaging(void)
2726 {
2727     WNDCLASS wndclass;
2728     HINSTANCE s_hinst;
2729
2730     /* Clean up on exit */
2731     atexit(CleanUpMessaging);
2732
2733     /* Register a window class - we only really care
2734      * about the window procedure
2735      */
2736     s_hinst = (HINSTANCE)GetModuleHandle(0);
2737     wndclass.style = 0;
2738     wndclass.lpfnWndProc = Messaging_WndProc;
2739     wndclass.cbClsExtra = 0;
2740     wndclass.cbWndExtra = 0;
2741     wndclass.hInstance = s_hinst;
2742     wndclass.hIcon = NULL;
2743     wndclass.hCursor = NULL;
2744     wndclass.hbrBackground = NULL;
2745     wndclass.lpszMenuName = NULL;
2746     wndclass.lpszClassName = VIM_CLASSNAME;
2747     RegisterClass(&wndclass);
2748
2749     /* Create the message window. It will be hidden, so the details don't
2750      * matter.  Don't use WS_OVERLAPPEDWINDOW, it will make a shortcut remove
2751      * focus from gvim. */
2752     message_window = CreateWindow(VIM_CLASSNAME, "",
2753                          WS_POPUPWINDOW | WS_CAPTION,
2754                          CW_USEDEFAULT, CW_USEDEFAULT,
2755                          100, 100, NULL, NULL,
2756                          s_hinst, NULL);
2757 }
2758
2759 /* Used by serverSendToVim() to find an alternate server name. */
2760 static char_u *altname_buf_ptr = NULL;
2761
2762 /*
2763  * Get the title of the window "hwnd", which is the Vim server name, in
2764  * "name[namelen]" and return the length.
2765  * Returns zero if window "hwnd" is not a Vim server.
2766  */
2767     static int
2768 getVimServerName(HWND hwnd, char *name, int namelen)
2769 {
2770     int         len;
2771     char        buffer[VIM_CLASSNAME_LEN + 1];
2772
2773     /* Ignore windows which aren't Vim message windows */
2774     len = GetClassName(hwnd, buffer, sizeof(buffer));
2775     if (len != VIM_CLASSNAME_LEN || STRCMP(buffer, VIM_CLASSNAME) != 0)
2776         return 0;
2777
2778     /* Get the title of the window */
2779     return GetWindowText(hwnd, name, namelen);
2780 }
2781
2782     static BOOL CALLBACK
2783 enumWindowsGetServer(HWND hwnd, LPARAM lparam)
2784 {
2785     struct      server_id *id = (struct server_id *)lparam;
2786     char        server[MAX_PATH];
2787
2788     /* Get the title of the window */
2789     if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2790         return TRUE;
2791
2792     /* If this is the server we're looking for, return its HWND */
2793     if (STRICMP(server, id->name) == 0)
2794     {
2795         id->hwnd = hwnd;
2796         return FALSE;
2797     }
2798
2799     /* If we are looking for an alternate server, remember this name. */
2800     if (altname_buf_ptr != NULL
2801             && STRNICMP(server, id->name, STRLEN(id->name)) == 0
2802             && vim_isdigit(server[STRLEN(id->name)]))
2803     {
2804         STRCPY(altname_buf_ptr, server);
2805         altname_buf_ptr = NULL;     /* don't use another name */
2806     }
2807
2808     /* Otherwise, keep looking */
2809     return TRUE;
2810 }
2811
2812     static BOOL CALLBACK
2813 enumWindowsGetNames(HWND hwnd, LPARAM lparam)
2814 {
2815     garray_T    *ga = (garray_T *)lparam;
2816     char        server[MAX_PATH];
2817
2818     /* Get the title of the window */
2819     if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2820         return TRUE;
2821
2822     /* Add the name to the list */
2823     ga_concat(ga, server);
2824     ga_concat(ga, "\n");
2825     return TRUE;
2826 }
2827
2828     static HWND
2829 findServer(char_u *name)
2830 {
2831     struct server_id id;
2832
2833     id.name = name;
2834     id.hwnd = 0;
2835
2836     EnumWindows(enumWindowsGetServer, (LPARAM)(&id));
2837
2838     return id.hwnd;
2839 }
2840
2841     void
2842 serverSetName(char_u *name)
2843 {
2844     char_u      *ok_name;
2845     HWND        hwnd = 0;
2846     int         i = 0;
2847     char_u      *p;
2848
2849     /* Leave enough space for a 9-digit suffix to ensure uniqueness! */
2850     ok_name = alloc((unsigned)STRLEN(name) + 10);
2851
2852     STRCPY(ok_name, name);
2853     p = ok_name + STRLEN(name);
2854
2855     for (;;)
2856     {
2857         /* This is inefficient - we're doing an EnumWindows loop for each
2858          * possible name. It would be better to grab all names in one go,
2859          * and scan the list each time...
2860          */
2861         hwnd = findServer(ok_name);
2862         if (hwnd == 0)
2863             break;
2864
2865         ++i;
2866         if (i >= 1000)
2867             break;
2868
2869         sprintf((char *)p, "%d", i);
2870     }
2871
2872     if (hwnd != 0)
2873         vim_free(ok_name);
2874     else
2875     {
2876         /* Remember the name */
2877         serverName = ok_name;
2878 #ifdef FEAT_TITLE
2879         need_maketitle = TRUE;  /* update Vim window title later */
2880 #endif
2881
2882         /* Update the message window title */
2883         SetWindowText(message_window, ok_name);
2884
2885 #ifdef FEAT_EVAL
2886         /* Set the servername variable */
2887         set_vim_var_string(VV_SEND_SERVER, serverName, -1);
2888 #endif
2889     }
2890 }
2891
2892     char_u *
2893 serverGetVimNames(void)
2894 {
2895     garray_T ga;
2896
2897     ga_init2(&ga, 1, 100);
2898
2899     EnumWindows(enumWindowsGetNames, (LPARAM)(&ga));
2900     ga_append(&ga, NUL);
2901
2902     return ga.ga_data;
2903 }
2904
2905     int
2906 serverSendReply(name, reply)
2907     char_u      *name;          /* Where to send. */
2908     char_u      *reply;         /* What to send. */
2909 {
2910     HWND        target;
2911     COPYDATASTRUCT data;
2912     long_u      n = 0;
2913
2914     /* The "name" argument is a magic cookie obtained from expand("<client>").
2915      * It should be of the form 0xXXXXX - i.e. a C hex literal, which is the
2916      * value of the client's message window HWND.
2917      */
2918     sscanf((char *)name, SCANF_HEX_LONG_U, &n);
2919     if (n == 0)
2920         return -1;
2921
2922     target = (HWND)n;
2923     if (!IsWindow(target))
2924         return -1;
2925
2926     data.dwData = COPYDATA_REPLY;
2927     data.cbData = (DWORD)STRLEN(reply) + 1;
2928     data.lpData = reply;
2929
2930     serverSendEnc(target);
2931     if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2932                                                              (LPARAM)(&data)))
2933         return 0;
2934
2935     return -1;
2936 }
2937
2938     int
2939 serverSendToVim(name, cmd, result, ptarget, asExpr, silent)
2940     char_u       *name;                 /* Where to send. */
2941     char_u       *cmd;                  /* What to send. */
2942     char_u       **result;              /* Result of eval'ed expression */
2943     void         *ptarget;              /* HWND of server */
2944     int          asExpr;                /* Expression or keys? */
2945     int          silent;                /* don't complain about no server */
2946 {
2947     HWND        target;
2948     COPYDATASTRUCT data;
2949     char_u      *retval = NULL;
2950     int         retcode = 0;
2951     char_u      altname_buf[MAX_PATH];
2952
2953     /* If the server name does not end in a digit then we look for an
2954      * alternate name.  e.g. when "name" is GVIM the we may find GVIM2. */
2955     if (STRLEN(name) > 1 && !vim_isdigit(name[STRLEN(name) - 1]))
2956         altname_buf_ptr = altname_buf;
2957     altname_buf[0] = NUL;
2958     target = findServer(name);
2959     altname_buf_ptr = NULL;
2960     if (target == 0 && altname_buf[0] != NUL)
2961         /* Use another server name we found. */
2962         target = findServer(altname_buf);
2963
2964     if (target == 0)
2965     {
2966         if (!silent)
2967             EMSG2(_(e_noserver), name);
2968         return -1;
2969     }
2970
2971     if (ptarget)
2972         *(HWND *)ptarget = target;
2973
2974     data.dwData = asExpr ? COPYDATA_EXPR : COPYDATA_KEYS;
2975     data.cbData = (DWORD)STRLEN(cmd) + 1;
2976     data.lpData = cmd;
2977
2978     serverSendEnc(target);
2979     if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2980                                                         (LPARAM)(&data)) == 0)
2981         return -1;
2982
2983     if (asExpr)
2984         retval = serverGetReply(target, &retcode, TRUE, TRUE);
2985
2986     if (result == NULL)
2987         vim_free(retval);
2988     else
2989         *result = retval; /* Caller assumes responsibility for freeing */
2990
2991     return retcode;
2992 }
2993
2994 /*
2995  * Bring the server to the foreground.
2996  */
2997     void
2998 serverForeground(name)
2999     char_u      *name;
3000 {
3001     HWND        target = findServer(name);
3002
3003     if (target != 0)
3004         SetForegroundWindow(target);
3005 }
3006
3007 /* Replies from server need to be stored until the client picks them up via
3008  * remote_read(). So we maintain a list of server-id/reply pairs.
3009  * Note that there could be multiple replies from one server pending if the
3010  * client is slow picking them up.
3011  * We just store the replies in a simple list. When we remove an entry, we
3012  * move list entries down to fill the gap.
3013  * The server ID is simply the HWND.
3014  */
3015 typedef struct
3016 {
3017     HWND        server;         /* server window */
3018     char_u      *reply;         /* reply string */
3019     int         expr_result;    /* 0 for REPLY, 1 for RESULT 2 for error */
3020 } reply_T;
3021
3022 static garray_T reply_list = {0, 0, sizeof(reply_T), 5, 0};
3023
3024 #define REPLY_ITEM(i) ((reply_T *)(reply_list.ga_data) + (i))
3025 #define REPLY_COUNT (reply_list.ga_len)
3026
3027 /* Flag which is used to wait for a reply */
3028 static int reply_received = 0;
3029
3030 /*
3031  * Store a reply.  "reply" must be allocated memory (or NULL).
3032  */
3033     static int
3034 save_reply(HWND server, char_u *reply, int expr)
3035 {
3036     reply_T *rep;
3037
3038     if (ga_grow(&reply_list, 1) == FAIL)
3039         return FAIL;
3040
3041     rep = REPLY_ITEM(REPLY_COUNT);
3042     rep->server = server;
3043     rep->reply = reply;
3044     rep->expr_result = expr;
3045     if (rep->reply == NULL)
3046         return FAIL;
3047
3048     ++REPLY_COUNT;
3049     reply_received = 1;
3050     return OK;
3051 }
3052
3053 /*
3054  * Get a reply from server "server".
3055  * When "expr_res" is non NULL, get the result of an expression, otherwise a
3056  * server2client() message.
3057  * When non NULL, point to return code. 0 => OK, -1 => ERROR
3058  * If "remove" is TRUE, consume the message, the caller must free it then.
3059  * if "wait" is TRUE block until a message arrives (or the server exits).
3060  */
3061     char_u *
3062 serverGetReply(HWND server, int *expr_res, int remove, int wait)
3063 {
3064     int         i;
3065     char_u      *reply;
3066     reply_T     *rep;
3067
3068     /* When waiting, loop until the message waiting for is received. */
3069     for (;;)
3070     {
3071         /* Reset this here, in case a message arrives while we are going
3072          * through the already received messages. */
3073         reply_received = 0;
3074
3075         for (i = 0; i < REPLY_COUNT; ++i)
3076         {
3077             rep = REPLY_ITEM(i);
3078             if (rep->server == server
3079                     && ((rep->expr_result != 0) == (expr_res != NULL)))
3080             {
3081                 /* Save the values we've found for later */
3082                 reply = rep->reply;
3083                 if (expr_res != NULL)
3084                     *expr_res = rep->expr_result == 1 ? 0 : -1;
3085
3086                 if (remove)
3087                 {
3088                     /* Move the rest of the list down to fill the gap */
3089                     mch_memmove(rep, rep + 1,
3090                                      (REPLY_COUNT - i - 1) * sizeof(reply_T));
3091                     --REPLY_COUNT;
3092                 }
3093
3094                 /* Return the reply to the caller, who takes on responsibility
3095                  * for freeing it if "remove" is TRUE. */
3096                 return reply;
3097             }
3098         }
3099
3100         /* If we got here, we didn't find a reply. Return immediately if the
3101          * "wait" parameter isn't set.  */
3102         if (!wait)
3103             break;
3104
3105         /* We need to wait for a reply. Enter a message loop until the
3106          * "reply_received" flag gets set. */
3107
3108         /* Loop until we receive a reply */
3109         while (reply_received == 0)
3110         {
3111             /* Wait for a SendMessage() call to us.  This could be the reply
3112              * we are waiting for.  Use a timeout of a second, to catch the
3113              * situation that the server died unexpectedly. */
3114             MsgWaitForMultipleObjects(0, NULL, TRUE, 1000, QS_ALLINPUT);
3115
3116             /* If the server has died, give up */
3117             if (!IsWindow(server))
3118                 return NULL;
3119
3120             serverProcessPendingMessages();
3121         }
3122     }
3123
3124     return NULL;
3125 }
3126
3127 /*
3128  * Process any messages in the Windows message queue.
3129  */
3130     void
3131 serverProcessPendingMessages(void)
3132 {
3133     MSG msg;
3134
3135     while (pPeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
3136     {
3137         TranslateMessage(&msg);
3138         pDispatchMessage(&msg);
3139     }
3140 }
3141
3142 #endif /* FEAT_CLIENTSERVER */
3143
3144 #if defined(FEAT_GUI) || (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) \
3145         || defined(PROTO)
3146
3147 struct charset_pair
3148 {
3149     char        *name;
3150     BYTE        charset;
3151 };
3152
3153 static struct charset_pair
3154 charset_pairs[] =
3155 {
3156     {"ANSI",            ANSI_CHARSET},
3157     {"CHINESEBIG5",     CHINESEBIG5_CHARSET},
3158     {"DEFAULT",         DEFAULT_CHARSET},
3159     {"HANGEUL",         HANGEUL_CHARSET},
3160     {"OEM",             OEM_CHARSET},
3161     {"SHIFTJIS",        SHIFTJIS_CHARSET},
3162     {"SYMBOL",          SYMBOL_CHARSET},
3163 #ifdef WIN3264
3164     {"ARABIC",          ARABIC_CHARSET},
3165     {"BALTIC",          BALTIC_CHARSET},
3166     {"EASTEUROPE",      EASTEUROPE_CHARSET},
3167     {"GB2312",          GB2312_CHARSET},
3168     {"GREEK",           GREEK_CHARSET},
3169     {"HEBREW",          HEBREW_CHARSET},
3170     {"JOHAB",           JOHAB_CHARSET},
3171     {"MAC",             MAC_CHARSET},
3172     {"RUSSIAN",         RUSSIAN_CHARSET},
3173     {"THAI",            THAI_CHARSET},
3174     {"TURKISH",         TURKISH_CHARSET},
3175 # if (!defined(_MSC_VER) || (_MSC_VER > 1010)) \
3176         && (!defined(__BORLANDC__) || (__BORLANDC__ > 0x0500))
3177     {"VIETNAMESE",      VIETNAMESE_CHARSET},
3178 # endif
3179 #endif
3180     {NULL,              0}
3181 };
3182
3183 /*
3184  * Convert a charset ID to a name.
3185  * Return NULL when not recognized.
3186  */
3187     char *
3188 charset_id2name(int id)
3189 {
3190     struct charset_pair *cp;
3191
3192     for (cp = charset_pairs; cp->name != NULL; ++cp)
3193         if ((BYTE)id == cp->charset)
3194             break;
3195     return cp->name;
3196 }
3197
3198 static const LOGFONT s_lfDefault =
3199 {
3200     -12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
3201     OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
3202     PROOF_QUALITY, FIXED_PITCH | FF_DONTCARE,
3203     "Fixedsys"  /* see _ReadVimIni */
3204 };
3205
3206 /* Initialise the "current height" to -12 (same as s_lfDefault) just
3207  * in case the user specifies a font in "guifont" with no size before a font
3208  * with an explicit size has been set. This defaults the size to this value
3209  * (-12 equates to roughly 9pt).
3210  */
3211 int current_font_height = -12;          /* also used in gui_w48.c */
3212
3213 /* Convert a string representing a point size into pixels. The string should
3214  * be a positive decimal number, with an optional decimal point (eg, "12", or
3215  * "10.5"). The pixel value is returned, and a pointer to the next unconverted
3216  * character is stored in *end. The flag "vertical" says whether this
3217  * calculation is for a vertical (height) size or a horizontal (width) one.
3218  */
3219     static int
3220 points_to_pixels(char_u *str, char_u **end, int vertical, long_i pprinter_dc)
3221 {
3222     int         pixels;
3223     int         points = 0;
3224     int         divisor = 0;
3225     HWND        hwnd = (HWND)0;
3226     HDC         hdc;
3227     HDC         printer_dc = (HDC)pprinter_dc;
3228
3229     while (*str != NUL)
3230     {
3231         if (*str == '.' && divisor == 0)
3232         {
3233             /* Start keeping a divisor, for later */
3234             divisor = 1;
3235         }
3236         else
3237         {
3238             if (!VIM_ISDIGIT(*str))
3239                 break;
3240
3241             points *= 10;
3242             points += *str - '0';
3243             divisor *= 10;
3244         }
3245         ++str;
3246     }
3247
3248     if (divisor == 0)
3249         divisor = 1;
3250
3251     if (printer_dc == NULL)
3252     {
3253         hwnd = GetDesktopWindow();
3254         hdc = GetWindowDC(hwnd);
3255     }
3256     else
3257         hdc = printer_dc;
3258
3259     pixels = MulDiv(points,
3260                     GetDeviceCaps(hdc, vertical ? LOGPIXELSY : LOGPIXELSX),
3261                     72 * divisor);
3262
3263     if (printer_dc == NULL)
3264         ReleaseDC(hwnd, hdc);
3265
3266     *end = str;
3267     return pixels;
3268 }
3269
3270 /*ARGSUSED*/
3271     static int CALLBACK
3272 font_enumproc(
3273     ENUMLOGFONT     *elf,
3274     NEWTEXTMETRIC   *ntm,
3275     int             type,
3276     LPARAM          lparam)
3277 {
3278     /* Return value:
3279      *    0 = terminate now (monospace & ANSI)
3280      *    1 = continue, still no luck...
3281      *    2 = continue, but we have an acceptable LOGFONT
3282      *        (monospace, not ANSI)
3283      * We use these values, as EnumFontFamilies returns 1 if the
3284      * callback function is never called. So, we check the return as
3285      * 0 = perfect, 2 = OK, 1 = no good...
3286      * It's not pretty, but it works!
3287      */
3288
3289     LOGFONT *lf = (LOGFONT *)(lparam);
3290
3291 #ifndef FEAT_PROPORTIONAL_FONTS
3292     /* Ignore non-monospace fonts without further ado */
3293     if ((ntm->tmPitchAndFamily & 1) != 0)
3294         return 1;
3295 #endif
3296
3297     /* Remember this LOGFONT as a "possible" */
3298     *lf = elf->elfLogFont;
3299
3300     /* Terminate the scan as soon as we find an ANSI font */
3301     if (lf->lfCharSet == ANSI_CHARSET
3302             || lf->lfCharSet == OEM_CHARSET
3303             || lf->lfCharSet == DEFAULT_CHARSET)
3304         return 0;
3305
3306     /* Continue the scan - we have a non-ANSI font */
3307     return 2;
3308 }
3309
3310     static int
3311 init_logfont(LOGFONT *lf)
3312 {
3313     int         n;
3314     HWND        hwnd = GetDesktopWindow();
3315     HDC         hdc = GetWindowDC(hwnd);
3316
3317     n = EnumFontFamilies(hdc,
3318                          (LPCSTR)lf->lfFaceName,
3319                          (FONTENUMPROC)font_enumproc,
3320                          (LPARAM)lf);
3321
3322     ReleaseDC(hwnd, hdc);
3323
3324     /* If we couldn't find a useable font, return failure */
3325     if (n == 1)
3326         return FAIL;
3327
3328     /* Tidy up the rest of the LOGFONT structure. We set to a basic
3329      * font - get_logfont() sets bold, italic, etc based on the user's
3330      * input.
3331      */
3332     lf->lfHeight = current_font_height;
3333     lf->lfWidth = 0;
3334     lf->lfItalic = FALSE;
3335     lf->lfUnderline = FALSE;
3336     lf->lfStrikeOut = FALSE;
3337     lf->lfWeight = FW_NORMAL;
3338
3339     /* Return success */
3340     return OK;
3341 }
3342
3343 /*
3344  * Get font info from "name" into logfont "lf".
3345  * Return OK for a valid name, FAIL otherwise.
3346  */
3347     int
3348 get_logfont(
3349     LOGFONT     *lf,
3350     char_u      *name,
3351     HDC         printer_dc,
3352     int         verbose)
3353 {
3354     char_u      *p;
3355     int         i;
3356     static LOGFONT *lastlf = NULL;
3357
3358     *lf = s_lfDefault;
3359     if (name == NULL)
3360         return OK;
3361
3362     if (STRCMP(name, "*") == 0)
3363     {
3364 #if defined(FEAT_GUI_W32)
3365         CHOOSEFONT      cf;
3366         /* if name is "*", bring up std font dialog: */
3367         vim_memset(&cf, 0, sizeof(cf));
3368         cf.lStructSize = sizeof(cf);
3369         cf.hwndOwner = s_hwnd;
3370         cf.Flags = CF_SCREENFONTS | CF_FIXEDPITCHONLY | CF_INITTOLOGFONTSTRUCT;
3371         if (lastlf != NULL)
3372             *lf = *lastlf;
3373         cf.lpLogFont = lf;
3374         cf.nFontType = 0 ; //REGULAR_FONTTYPE;
3375         if (ChooseFont(&cf))
3376             goto theend;
3377 #else
3378         return FAIL;
3379 #endif
3380     }
3381
3382     /*
3383      * Split name up, it could be <name>:h<height>:w<width> etc.
3384      */
3385     for (p = name; *p && *p != ':'; p++)
3386     {
3387         if (p - name + 1 > LF_FACESIZE)
3388             return FAIL;                        /* Name too long */
3389         lf->lfFaceName[p - name] = *p;
3390     }
3391     if (p != name)
3392         lf->lfFaceName[p - name] = NUL;
3393
3394     /* First set defaults */
3395     lf->lfHeight = -12;
3396     lf->lfWidth = 0;
3397     lf->lfWeight = FW_NORMAL;
3398     lf->lfItalic = FALSE;
3399     lf->lfUnderline = FALSE;
3400     lf->lfStrikeOut = FALSE;
3401
3402     /*
3403      * If the font can't be found, try replacing '_' by ' '.
3404      */
3405     if (init_logfont(lf) == FAIL)
3406     {
3407         int     did_replace = FALSE;
3408
3409         for (i = 0; lf->lfFaceName[i]; ++i)
3410             if (lf->lfFaceName[i] == '_')
3411             {
3412                 lf->lfFaceName[i] = ' ';
3413                 did_replace = TRUE;
3414             }
3415         if (!did_replace || init_logfont(lf) == FAIL)
3416             return FAIL;
3417     }
3418
3419     while (*p == ':')
3420         p++;
3421
3422     /* Set the values found after ':' */
3423     while (*p)
3424     {
3425         switch (*p++)
3426         {
3427             case 'h':
3428                 lf->lfHeight = - points_to_pixels(p, &p, TRUE, (long_i)printer_dc);
3429                 break;
3430             case 'w':
3431                 lf->lfWidth = points_to_pixels(p, &p, FALSE, (long_i)printer_dc);
3432                 break;
3433             case 'b':
3434 #ifndef MSWIN16_FASTTEXT
3435                 lf->lfWeight = FW_BOLD;
3436 #endif
3437                 break;
3438             case 'i':
3439 #ifndef MSWIN16_FASTTEXT
3440                 lf->lfItalic = TRUE;
3441 #endif
3442                 break;
3443             case 'u':
3444                 lf->lfUnderline = TRUE;
3445                 break;
3446             case 's':
3447                 lf->lfStrikeOut = TRUE;
3448                 break;
3449             case 'c':
3450                 {
3451                     struct charset_pair *cp;
3452
3453                     for (cp = charset_pairs; cp->name != NULL; ++cp)
3454                         if (STRNCMP(p, cp->name, strlen(cp->name)) == 0)
3455                         {
3456                             lf->lfCharSet = cp->charset;
3457                             p += strlen(cp->name);
3458                             break;
3459                         }
3460                     if (cp->name == NULL && verbose)
3461                     {
3462                         vim_snprintf((char *)IObuff, IOSIZE,
3463                                 _("E244: Illegal charset name \"%s\" in font name \"%s\""), p, name);
3464                         EMSG(IObuff);
3465                         break;
3466                     }
3467                     break;
3468                 }
3469             default:
3470                 if (verbose)
3471                 {
3472                     vim_snprintf((char *)IObuff, IOSIZE,
3473                             _("E245: Illegal char '%c' in font name \"%s\""),
3474                             p[-1], name);
3475                     EMSG(IObuff);
3476                 }
3477                 return FAIL;
3478         }
3479         while (*p == ':')
3480             p++;
3481     }
3482
3483 #if defined(FEAT_GUI_W32)
3484 theend:
3485 #endif
3486     /* ron: init lastlf */
3487     if (printer_dc == NULL)
3488     {
3489         vim_free(lastlf);
3490         lastlf = (LOGFONT *)alloc(sizeof(LOGFONT));
3491         if (lastlf != NULL)
3492             mch_memmove(lastlf, lf, sizeof(LOGFONT));
3493     }
3494
3495     return OK;
3496 }
3497
3498 #endif /* defined(FEAT_GUI) || defined(FEAT_PRINTER) */