Add pcomplete support for hosts defined in .ssh/config.
[emacs.git] / src / w32select.c
blobc323e34fa57ad1064defe32829816a4860fd1de3
1 /* Selection processing for Emacs on the Microsoft W32 API.
3 Copyright (C) 1993, 1994, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
4 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 /* Written by Kevin Gallo, Benjamin Riefenstahl */
25 * Notes on usage of selection-coding-system and
26 * next-selection-coding-system on MS Windows:
28 * The selection coding system variables apply only to the version of
29 * the clipboard data that is closest in type, i.e. when a 16-bit
30 * Unicode coding system is given, they apply to he Unicode clipboard
31 * (CF_UNICODETEXT), when a well-known console codepage is given, they
32 * apply to the console version of the clipboard data (CF_OEMTEXT),
33 * else they apply to the normal 8-bit text clipboard (CF_TEXT).
35 * When pasting (getting data from the OS), the clipboard format that
36 * matches the {next-}selection-coding-system is retrieved. If
37 * Unicode is requested, but not available, 8-bit text (CF_TEXT) is
38 * used. In all other cases the OS will transparently convert
39 * formats, so no other fallback is needed.
41 * When copying or cutting (sending data to the OS), the data is
42 * announced and stored internally, but only actually rendered on
43 * request. The requester determines the format provided. The
44 * {next-}selection-coding-system is only used, when its corresponding
45 * clipboard type matches the type requested.
47 * Scenarios to use the facilities for customizing the selection
48 * coding system are:
50 * ;; Generally use KOI8-R instead of the russian MS codepage for
51 * ;; the 8-bit clipboard.
52 * (set-selection-coding-system 'koi8-r-dos)
54 * Or
56 * ;; Create a special clipboard copy function that uses codepage
57 * ;; 1253 (Greek) to copy Greek text to a specific non-Unicode
58 * ;; application.
59 * (defun greek-copy (beg end)
60 * (interactive "r")
61 * (set-next-selection-coding-system 'cp1253-dos)
62 * (copy-region-as-kill beg end))
63 * (global-set-key "\C-c\C-c" 'greek-copy)
67 * Ideas for further directions:
69 * The encoding and decoding routines could be moved to Lisp code
70 * similar to how xselect.c does it (using well-known routine names
71 * for the delayed rendering). If the definition of which clipboard
72 * types should be supported is also moved to Lisp, functionality
73 * could be expanded to CF_HTML, CF_RTF and maybe other types.
76 #include <config.h>
77 #include <setjmp.h>
78 #include "lisp.h"
79 #include "w32term.h" /* for all of the w32 includes */
80 #include "w32heap.h" /* os_subtype */
81 #include "blockinput.h"
82 #include "keyboard.h" /* cmd_error_internal() */
83 #include "charset.h"
84 #include "coding.h"
85 #include "character.h"
86 #include "composite.h"
89 static HGLOBAL convert_to_handle_as_ascii (void);
90 static HGLOBAL convert_to_handle_as_coded (Lisp_Object coding_system);
91 static Lisp_Object render (Lisp_Object oformat);
92 static Lisp_Object render_locale (void);
93 static Lisp_Object render_all (Lisp_Object ignore);
94 static void run_protected (Lisp_Object (*code) (Lisp_Object), Lisp_Object arg);
95 static Lisp_Object lisp_error_handler (Lisp_Object error);
96 static LRESULT CALLBACK owner_callback (HWND win, UINT msg,
97 WPARAM wp, LPARAM lp);
98 static HWND create_owner (void);
100 static void setup_config (void);
101 static BOOL WINAPI enum_locale_callback (/*const*/ char* loc_string);
102 static UINT cp_from_locale (LCID lcid, UINT format);
103 static Lisp_Object coding_from_cp (UINT codepage);
104 static Lisp_Object validate_coding_system (Lisp_Object coding_system);
105 static void setup_windows_coding_system (Lisp_Object coding_system,
106 struct coding_system * coding);
109 /* A remnant from X11: Symbol for the CLIPBORD selection type. Other
110 selections are not used on Windows, so we don't need symbols for
111 PRIMARY and SECONDARY. */
112 Lisp_Object QCLIPBOARD;
114 /* Internal pseudo-constants, initialized in globals_of_w32select()
115 based on current system parameters. */
116 static LCID DEFAULT_LCID;
117 static UINT ANSICP, OEMCP;
118 static Lisp_Object QUNICODE, QANSICP, QOEMCP;
120 /* A hidden window just for the clipboard management. */
121 static HWND clipboard_owner;
122 /* A flag to tell WM_DESTROYCLIPBOARD who is to blame this time (just
123 checking GetClipboardOwner() doesn't work, sadly). */
124 static int modifying_clipboard = 0;
126 /* Configured transfer parameters, based on the last inspection of
127 selection-coding-system. */
128 static Lisp_Object cfg_coding_system;
129 static UINT cfg_codepage;
130 static LCID cfg_lcid;
131 static UINT cfg_clipboard_type;
133 /* The current state for delayed rendering. */
134 static Lisp_Object current_text;
135 static Lisp_Object current_coding_system;
136 static int current_requires_encoding, current_num_nls;
137 static UINT current_clipboard_type;
138 static LCID current_lcid;
140 #if TRACE
141 #define ONTRACE(stmt) stmt
142 #else
143 #define ONTRACE(stmt) /*stmt*/
144 #endif
147 /* This function assumes that there is no multibyte character in
148 current_text, so we can short-cut encoding. */
150 static HGLOBAL
151 convert_to_handle_as_ascii (void)
153 HGLOBAL htext = NULL;
154 int nbytes;
155 int truelen;
156 unsigned char *src;
157 unsigned char *dst;
159 ONTRACE (fprintf (stderr, "convert_to_handle_as_ascii\n"));
161 nbytes = SBYTES (current_text) + 1;
162 src = SDATA (current_text);
164 /* We need to add to the size the number of LF chars where we have
165 to insert CR chars (the standard CF_TEXT clipboard format uses
166 CRLF line endings, while Emacs uses just LF internally). */
168 truelen = nbytes + current_num_nls;
170 if ((htext = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, truelen)) == NULL)
171 return NULL;
173 if ((dst = (unsigned char *) GlobalLock (htext)) == NULL)
175 GlobalFree (htext);
176 return NULL;
179 /* convert to CRLF line endings expected by clipboard */
180 while (1)
182 unsigned char *next;
183 /* copy next line or remaining bytes including '\0' */
184 next = _memccpy (dst, src, '\n', nbytes);
185 if (next)
187 /* copied one line ending with '\n' */
188 int copied = next - dst;
189 nbytes -= copied;
190 src += copied;
191 /* insert '\r' before '\n' */
192 next[-1] = '\r';
193 next[0] = '\n';
194 dst = next + 1;
196 else
197 /* copied remaining partial line -> now finished */
198 break;
201 GlobalUnlock (htext);
203 return htext;
206 /* This function assumes that there are multibyte or NUL characters in
207 current_text, or that we need to construct Unicode. It runs the
208 text through the encoding machinery. */
210 static HGLOBAL
211 convert_to_handle_as_coded (Lisp_Object coding_system)
213 HGLOBAL htext;
214 unsigned char *dst = NULL;
215 struct coding_system coding;
217 ONTRACE (fprintf (stderr, "convert_to_handle_as_coded: %s\n",
218 SDATA (SYMBOL_NAME (coding_system))));
220 setup_windows_coding_system (coding_system, &coding);
221 coding.dst_bytes = SBYTES (current_text) * 2;
222 coding.destination = (unsigned char *) xmalloc (coding.dst_bytes);
223 encode_coding_object (&coding, current_text, 0, 0,
224 SCHARS (current_text), SBYTES (current_text), Qnil);
226 htext = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, coding.produced +2);
228 if (htext != NULL)
229 dst = (unsigned char *) GlobalLock (htext);
231 if (dst != NULL)
233 memcpy (dst, coding.destination, coding.produced);
234 /* Add the string terminator. Add two NULs in case we are
235 producing Unicode here. */
236 dst[coding.produced] = dst[coding.produced+1] = '\0';
238 GlobalUnlock (htext);
241 xfree (coding.destination);
243 return htext;
246 static Lisp_Object
247 render (Lisp_Object oformat)
249 HGLOBAL htext = NULL;
250 UINT format = XFASTINT (oformat);
252 ONTRACE (fprintf (stderr, "render\n"));
254 if (NILP (current_text))
255 return Qnil;
257 if (current_requires_encoding || format == CF_UNICODETEXT)
259 if (format == current_clipboard_type)
260 htext = convert_to_handle_as_coded (current_coding_system);
261 else
262 switch (format)
264 case CF_UNICODETEXT:
265 htext = convert_to_handle_as_coded (QUNICODE);
266 break;
267 case CF_TEXT:
268 case CF_OEMTEXT:
270 Lisp_Object cs;
271 cs = coding_from_cp (cp_from_locale (current_lcid, format));
272 htext = convert_to_handle_as_coded (cs);
273 break;
277 else
278 htext = convert_to_handle_as_ascii ();
280 ONTRACE (fprintf (stderr, "render: htext = 0x%08X\n", (unsigned) htext));
282 if (htext == NULL)
283 return Qnil;
285 if (SetClipboardData (format, htext) == NULL)
287 GlobalFree (htext);
288 return Qnil;
291 return Qt;
294 static Lisp_Object
295 render_locale (void)
297 HANDLE hlocale = NULL;
298 LCID * lcid_ptr;
300 ONTRACE (fprintf (stderr, "render_locale\n"));
302 if (current_lcid == LOCALE_NEUTRAL || current_lcid == DEFAULT_LCID)
303 return Qt;
305 hlocale = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, sizeof (current_lcid));
306 if (hlocale == NULL)
307 return Qnil;
309 if ((lcid_ptr = (LCID *) GlobalLock (hlocale)) == NULL)
311 GlobalFree (hlocale);
312 return Qnil;
315 *lcid_ptr = current_lcid;
316 GlobalUnlock (hlocale);
318 if (SetClipboardData (CF_LOCALE, hlocale) == NULL)
320 GlobalFree (hlocale);
321 return Qnil;
324 return Qt;
327 /* At the end of the program, we want to ensure that our clipboard
328 data survives us. This code will do that. */
330 static Lisp_Object
331 render_all (Lisp_Object ignore)
333 ONTRACE (fprintf (stderr, "render_all\n"));
335 /* According to the docs we should not call OpenClipboard() here,
336 but testing on W2K and working code in other projects shows that
337 it is actually necessary. */
339 OpenClipboard (NULL);
341 /* There is no usefull means to report errors here, there are none
342 expected anyway, and even if there were errors, they wouldn't do
343 any harm. So we just go ahead and do what has to be done without
344 bothering with error handling. */
346 ++modifying_clipboard;
347 EmptyClipboard ();
348 --modifying_clipboard;
350 /* For text formats that we don't render here, the OS can use its
351 own translation rules instead, so we don't really need to offer
352 everything. To minimize memory consumption we cover three
353 possible situations based on our primary format as detected from
354 selection-coding-system (see setup_config()):
356 - Post CF_TEXT only. Let the OS convert to CF_OEMTEXT and the OS
357 (on NT) or the application (on 9x/Me) convert to
358 CF_UNICODETEXT.
360 - Post CF_OEMTEXT only. Similar automatic conversions happen as
361 for CF_TEXT.
363 - Post CF_UNICODETEXT + CF_TEXT. 9x itself ignores
364 CF_UNICODETEXT, even though some applications can still handle
367 Note 1: We render the less capable CF_TEXT *before* the more
368 capable CF_UNICODETEXT, to prevent clobbering through automatic
369 conversions, just in case.
371 Note 2: We could check os_subtype here and only render the
372 additional CF_TEXT on 9x/Me. But OTOH with
373 current_clipboard_type == CF_UNICODETEXT we don't involve the
374 automatic conversions anywhere else, so to get consistent
375 results, we probably don't want to rely on it here either. */
377 render_locale ();
379 if (current_clipboard_type == CF_UNICODETEXT)
380 render (make_number (CF_TEXT));
381 render (make_number (current_clipboard_type));
383 CloseClipboard ();
385 return Qnil;
388 static void
389 run_protected (Lisp_Object (*code) (Lisp_Object), Lisp_Object arg)
391 /* FIXME: This works but it doesn't feel right. Too much fiddling
392 with global variables and calling strange looking functions. Is
393 this really the right way to run Lisp callbacks? */
395 int owfi;
397 BLOCK_INPUT;
399 /* Fsignal calls abort() if it sees that waiting_for_input is
400 set. */
401 owfi = waiting_for_input;
402 waiting_for_input = 0;
404 internal_condition_case_1 (code, arg, Qt, lisp_error_handler);
406 waiting_for_input = owfi;
408 UNBLOCK_INPUT;
411 static Lisp_Object
412 lisp_error_handler (Lisp_Object error)
414 Vsignaling_function = Qnil;
415 cmd_error_internal (error, "Error in delayed clipboard rendering: ");
416 Vinhibit_quit = Qt;
417 return Qt;
421 static LRESULT CALLBACK
422 owner_callback (HWND win, UINT msg, WPARAM wp, LPARAM lp)
424 switch (msg)
426 case WM_RENDERFORMAT:
427 ONTRACE (fprintf (stderr, "WM_RENDERFORMAT\n"));
428 run_protected (render, make_number (wp));
429 return 0;
431 case WM_RENDERALLFORMATS:
432 ONTRACE (fprintf (stderr, "WM_RENDERALLFORMATS\n"));
433 run_protected (render_all, Qnil);
434 return 0;
436 case WM_DESTROYCLIPBOARD:
437 if (!modifying_clipboard)
439 ONTRACE (fprintf (stderr, "WM_DESTROYCLIPBOARD (other)\n"));
440 current_text = Qnil;
441 current_coding_system = Qnil;
443 else
445 ONTRACE (fprintf (stderr, "WM_DESTROYCLIPBOARD (self)\n"));
447 return 0;
449 case WM_DESTROY:
450 if (win == clipboard_owner)
451 clipboard_owner = NULL;
452 break;
455 return DefWindowProc (win, msg, wp, lp);
458 static HWND
459 create_owner (void)
461 static const char CLASSNAME[] = "Emacs Clipboard";
462 WNDCLASS wc;
464 memset (&wc, 0, sizeof (wc));
465 wc.lpszClassName = CLASSNAME;
466 wc.lpfnWndProc = owner_callback;
467 RegisterClass (&wc);
469 return CreateWindow (CLASSNAME, CLASSNAME, 0, 0, 0, 0, 0, NULL, NULL,
470 NULL, NULL);
473 /* Called on exit by term_ntproc() in w32.c */
475 void
476 term_w32select (void)
478 /* This is needed to trigger WM_RENDERALLFORMATS. */
479 if (clipboard_owner != NULL)
480 DestroyWindow (clipboard_owner);
483 static void
484 setup_config (void)
486 const char *coding_name;
487 const char *cp;
488 char *end;
489 int slen;
490 Lisp_Object coding_system;
491 Lisp_Object dos_coding_system;
493 CHECK_SYMBOL (Vselection_coding_system);
495 coding_system = NILP (Vnext_selection_coding_system) ?
496 Vselection_coding_system : Vnext_selection_coding_system;
498 dos_coding_system = validate_coding_system (coding_system);
499 if (NILP (dos_coding_system))
500 Fsignal (Qerror,
501 list2 (build_string ("Coding system is invalid or doesn't have "
502 "an eol variant for dos line ends"),
503 coding_system));
505 /* Check if we have it cached */
506 if (!NILP (cfg_coding_system)
507 && EQ (cfg_coding_system, dos_coding_system))
508 return;
509 cfg_coding_system = dos_coding_system;
511 /* Set some sensible fallbacks */
512 cfg_codepage = ANSICP;
513 cfg_lcid = LOCALE_NEUTRAL;
514 cfg_clipboard_type = CF_TEXT;
516 /* Interpret the coding system symbol name */
517 coding_name = SDATA (SYMBOL_NAME (cfg_coding_system));
519 /* "(.*-)?utf-16.*" -> CF_UNICODETEXT */
520 cp = strstr (coding_name, "utf-16");
521 if (cp != NULL && (cp == coding_name || cp[-1] == '-'))
523 cfg_clipboard_type = CF_UNICODETEXT;
524 return;
527 /* "cp[0-9]+.*" or "windows-[0-9]+.*" -> CF_TEXT or CF_OEMTEXT */
528 slen = strlen (coding_name);
529 if (slen >= 4 && coding_name[0] == 'c' && coding_name[1] == 'p')
530 cp = coding_name + 2;
531 else if (slen >= 10 && memcmp (coding_name, "windows-", 8) == 0)
532 cp = coding_name + 8;
533 else
534 return;
536 end = (char*)cp;
537 cfg_codepage = strtol (cp, &end, 10);
539 /* Error return from strtol() or number of digits < 2 -> Restore the
540 default and drop it. */
541 if (cfg_codepage == 0 || (end-cp) < 2 )
543 cfg_codepage = ANSICP;
544 return;
547 /* Is it the currently active system default? */
548 if (cfg_codepage == ANSICP)
550 /* cfg_clipboard_type = CF_TEXT; */
551 return;
553 if (cfg_codepage == OEMCP)
555 cfg_clipboard_type = CF_OEMTEXT;
556 return;
559 /* Else determine a suitable locale the hard way. */
560 EnumSystemLocales (enum_locale_callback, LCID_INSTALLED);
563 static BOOL WINAPI
564 enum_locale_callback (/*const*/ char* loc_string)
566 LCID lcid;
567 UINT codepage;
569 lcid = strtoul (loc_string, NULL, 16);
571 /* Is the wanted codepage the "ANSI" codepage for this locale? */
572 codepage = cp_from_locale (lcid, CF_TEXT);
573 if (codepage == cfg_codepage)
575 cfg_lcid = lcid;
576 cfg_clipboard_type = CF_TEXT;
577 return FALSE; /* Stop enumeration */
580 /* Is the wanted codepage the OEM codepage for this locale? */
581 codepage = cp_from_locale (lcid, CF_OEMTEXT);
582 if (codepage == cfg_codepage)
584 cfg_lcid = lcid;
585 cfg_clipboard_type = CF_OEMTEXT;
586 return FALSE; /* Stop enumeration */
589 return TRUE; /* Continue enumeration */
592 static UINT
593 cp_from_locale (LCID lcid, UINT format)
595 char buffer[20] = "";
596 UINT variant, cp;
598 variant =
599 format == CF_TEXT ? LOCALE_IDEFAULTANSICODEPAGE : LOCALE_IDEFAULTCODEPAGE;
601 GetLocaleInfo (lcid, variant, buffer, sizeof (buffer));
602 cp = strtoul (buffer, NULL, 10);
604 if (cp == CP_ACP)
605 return ANSICP;
606 else if (cp == CP_OEMCP)
607 return OEMCP;
608 else
609 return cp;
612 static Lisp_Object
613 coding_from_cp (UINT codepage)
615 char buffer[30];
616 sprintf (buffer, "cp%d-dos", (int) codepage);
617 return intern (buffer);
618 /* We don't need to check that this coding system actually exists
619 right here, because that is done later for all coding systems
620 used, regardless of where they originate. */
623 static Lisp_Object
624 validate_coding_system (Lisp_Object coding_system)
626 Lisp_Object eol_type;
628 /* Make sure the input is valid. */
629 if (NILP (Fcoding_system_p (coding_system)))
630 return Qnil;
632 /* Make sure we use a DOS coding system as mandated by the system
633 specs. */
634 eol_type = Fcoding_system_eol_type (coding_system);
636 /* Already a DOS coding system? */
637 if (EQ (eol_type, make_number (1)))
638 return coding_system;
640 /* Get EOL_TYPE vector of the base of CODING_SYSTEM. */
641 if (!VECTORP (eol_type))
643 eol_type = Fcoding_system_eol_type (Fcoding_system_base (coding_system));
644 if (!VECTORP (eol_type))
645 return Qnil;
648 return AREF (eol_type, 1);
651 static void
652 setup_windows_coding_system (Lisp_Object coding_system,
653 struct coding_system * coding)
655 memset (coding, 0, sizeof (*coding));
656 setup_coding_system (coding_system, coding);
658 /* Unset CODING_ANNOTATE_COMPOSITION_MASK. Previous code had
659 comments about crashes in encode_coding_iso2022 trying to
660 dereference a null pointer when composition was on. Selection
661 data should not contain any composition sequence on Windows.
663 CODING_ANNOTATION_MASK also includes
664 CODING_ANNOTATE_DIRECTION_MASK and CODING_ANNOTATE_CHARSET_MASK,
665 which both apply to ISO6429 only. We don't know if these really
666 need to be unset on Windows, but it probably doesn't hurt
667 either. */
668 coding->mode &= ~CODING_ANNOTATION_MASK;
669 coding->mode |= CODING_MODE_LAST_BLOCK | CODING_MODE_SAFE_ENCODING;
674 DEFUN ("w32-set-clipboard-data", Fw32_set_clipboard_data,
675 Sw32_set_clipboard_data, 1, 2, 0,
676 doc: /* This sets the clipboard data to the given text. */)
677 (Lisp_Object string, Lisp_Object ignored)
679 BOOL ok = TRUE;
680 int nbytes;
681 unsigned char *src;
682 unsigned char *dst;
683 unsigned char *end;
685 /* This parameter used to be the current frame, but we don't use
686 that any more. */
687 (void) ignored;
689 CHECK_STRING (string);
691 setup_config ();
693 current_text = string;
694 current_coding_system = cfg_coding_system;
695 current_clipboard_type = cfg_clipboard_type;
696 current_lcid = cfg_lcid;
697 current_num_nls = 0;
698 current_requires_encoding = 0;
700 BLOCK_INPUT;
702 /* Check for non-ASCII characters. While we are at it, count the
703 number of LFs, so we know how many CRs we will have to add later
704 (just in the case where we can use our internal ASCII rendering,
705 see code and comment in convert_to_handle_as_ascii() above). */
706 nbytes = SBYTES (string);
707 src = SDATA (string);
709 for (dst = src, end = src+nbytes; dst < end; dst++)
711 if (*dst == '\n')
712 current_num_nls++;
713 else if (*dst >= 0x80 || *dst == 0)
715 current_requires_encoding = 1;
716 break;
720 if (!current_requires_encoding)
722 /* If all we have is ASCII we don't need to pretend we offer
723 anything fancy. */
724 current_coding_system = Qraw_text;
725 current_clipboard_type = CF_TEXT;
726 current_lcid = LOCALE_NEUTRAL;
729 if (!OpenClipboard (clipboard_owner))
730 goto error;
732 ++modifying_clipboard;
733 ok = EmptyClipboard ();
734 --modifying_clipboard;
736 /* If we have something non-ASCII we may want to set a locale. We
737 do that directly (non-delayed), as it's just a small bit. */
738 if (ok)
739 ok = !NILP (render_locale ());
741 if (ok)
743 if (clipboard_owner == NULL)
745 /* If for some reason we don't have a clipboard_owner, we
746 just set the text format as chosen by the configuration
747 and than forget about the whole thing. */
748 ok = !NILP (render (make_number (current_clipboard_type)));
749 current_text = Qnil;
750 current_coding_system = Qnil;
752 else
754 /* Advertise all supported formats so that whatever the
755 requester chooses, only one encoding step needs to be
756 made. This is intentionally different from what we do in
757 the handler for WM_RENDERALLFORMATS. */
758 SetClipboardData (CF_UNICODETEXT, NULL);
759 SetClipboardData (CF_TEXT, NULL);
760 SetClipboardData (CF_OEMTEXT, NULL);
764 CloseClipboard ();
766 /* With delayed rendering we haven't really "used" this coding
767 system yet, and it's even unclear if we ever will. But this is a
768 way to tell the upper level what we *would* use under ideal
769 circumstances.
771 We don't signal the actually used coding-system later when we
772 finally render, because that can happen at any time and we don't
773 want to disturb the "foreground" action. */
774 if (ok)
775 Vlast_coding_system_used = current_coding_system;
777 Vnext_selection_coding_system = Qnil;
779 if (ok) goto done;
781 error:
783 ok = FALSE;
784 current_text = Qnil;
785 current_coding_system = Qnil;
787 done:
788 UNBLOCK_INPUT;
790 return (ok ? string : Qnil);
794 DEFUN ("w32-get-clipboard-data", Fw32_get_clipboard_data,
795 Sw32_get_clipboard_data, 0, 1, 0,
796 doc: /* This gets the clipboard data in text format. */)
797 (Lisp_Object ignored)
799 HGLOBAL htext;
800 Lisp_Object ret = Qnil;
801 UINT actual_clipboard_type;
802 int use_configured_coding_system = 1;
804 /* This parameter used to be the current frame, but we don't use
805 that any more. */
806 (void) ignored;
808 /* Don't pass our own text from the clipboard (which might be
809 troublesome if the killed text includes null characters). */
810 if (!NILP (current_text))
811 return ret;
813 setup_config ();
814 actual_clipboard_type = cfg_clipboard_type;
816 BLOCK_INPUT;
818 if (!OpenClipboard (clipboard_owner))
819 goto done;
821 if ((htext = GetClipboardData (actual_clipboard_type)) == NULL)
823 /* If we want CF_UNICODETEXT but can't get it, the current
824 coding system is useless. OTOH we can still try and decode
825 CF_TEXT based on the locale that the system gives us and that
826 we get down below. */
827 if (actual_clipboard_type == CF_UNICODETEXT)
829 htext = GetClipboardData (CF_TEXT);
830 if (htext != NULL)
832 actual_clipboard_type = CF_TEXT;
833 use_configured_coding_system = 0;
837 if (htext == NULL)
838 goto closeclip;
841 unsigned char *src;
842 unsigned char *dst;
843 int nbytes;
844 int truelen;
845 int require_decoding = 0;
847 if ((src = (unsigned char *) GlobalLock (htext)) == NULL)
848 goto closeclip;
850 /* If the clipboard data contains any non-ascii code, we need to
851 decode it with a coding system. */
852 if (actual_clipboard_type == CF_UNICODETEXT)
854 nbytes = lstrlenW ((WCHAR *)src) * 2;
855 require_decoding = 1;
857 else
859 int i;
861 nbytes = strlen (src);
863 for (i = 0; i < nbytes; i++)
865 if (src[i] >= 0x80)
867 require_decoding = 1;
868 break;
873 if (require_decoding)
875 struct coding_system coding;
876 Lisp_Object coding_system = Qnil;
877 Lisp_Object dos_coding_system;
879 /* `next-selection-coding-system' should override everything,
880 even when the locale passed by the system disagrees. The
881 only exception is when `next-selection-coding-system'
882 requested CF_UNICODETEXT and we couldn't get that. */
883 if (use_configured_coding_system
884 && !NILP (Vnext_selection_coding_system))
885 coding_system = Vnext_selection_coding_system;
887 /* If we have CF_TEXT or CF_OEMTEXT, we want to check out
888 CF_LOCALE, too. */
889 else if (actual_clipboard_type != CF_UNICODETEXT)
891 HGLOBAL hlocale;
892 LCID lcid = DEFAULT_LCID;
893 UINT cp;
895 /* Documentation says that the OS always generates
896 CF_LOCALE info automatically, so the locale handle
897 should always be present. Fact is that this is not
898 always true on 9x ;-(. */
899 hlocale = GetClipboardData (CF_LOCALE);
900 if (hlocale != NULL)
902 const LCID * lcid_ptr;
903 lcid_ptr = (const LCID *) GlobalLock (hlocale);
904 if (lcid_ptr != NULL)
906 lcid = *lcid_ptr;
907 GlobalUnlock (hlocale);
910 /* 9x has garbage as the sort order (to be exact there
911 is another instance of the language id in the upper
912 word). We don't care about sort order anyway, so
913 we just filter out the unneeded mis-information to
914 avoid irritations. */
915 lcid = MAKELCID (LANGIDFROMLCID (lcid), SORT_DEFAULT);
918 /* If we are using fallback from CF_UNICODETEXT, we can't
919 use the configured coding system. Also we don't want
920 to use it, if the system has supplied us with a locale
921 and it is not just the system default. */
922 if (!use_configured_coding_system || lcid != DEFAULT_LCID)
924 cp = cp_from_locale (lcid, actual_clipboard_type);
925 /* If it's just our current standard setting anyway,
926 use the coding system that the user has selected.
927 Otherwise create a new spec to match the locale
928 that was specified by the other side or the
929 system. */
930 if (!use_configured_coding_system || cp != cfg_codepage)
931 coding_system = coding_from_cp (cp);
935 if (NILP (coding_system))
936 coding_system = Vselection_coding_system;
937 Vnext_selection_coding_system = Qnil;
939 dos_coding_system = validate_coding_system (coding_system);
940 if (!NILP (dos_coding_system))
942 setup_windows_coding_system (dos_coding_system, &coding);
943 coding.source = src;
944 decode_coding_object (&coding, Qnil, 0, 0, nbytes, nbytes, Qt);
945 ret = coding.dst_object;
947 Vlast_coding_system_used = CODING_ID_NAME (coding.id);
950 else
952 /* FIXME: We may want to repeat the code in this branch for
953 the Unicode case. */
955 /* Need to know final size after CR chars are removed because
956 we can't change the string size manually, and doing an
957 extra copy is silly. We only remove CR when it appears as
958 part of CRLF. */
960 truelen = nbytes;
961 dst = src;
962 /* avoid using strchr because it recomputes the length everytime */
963 while ((dst = memchr (dst, '\r', nbytes - (dst - src))) != NULL)
965 if (dst[1] == '\n') /* safe because of trailing '\0' */
966 truelen--;
967 dst++;
970 ret = make_uninit_string (truelen);
972 /* Convert CRLF line endings (the standard CF_TEXT clipboard
973 format) to LF endings as used internally by Emacs. */
975 dst = SDATA (ret);
976 while (1)
978 unsigned char *next;
979 /* copy next line or remaining bytes excluding '\0' */
980 next = _memccpy (dst, src, '\r', nbytes);
981 if (next)
983 /* copied one line ending with '\r' */
984 int copied = next - dst;
985 nbytes -= copied;
986 dst += copied;
987 src += copied;
988 if (*src == '\n')
989 dst--; /* overwrite '\r' with '\n' */
991 else
992 /* copied remaining partial line -> now finished */
993 break;
996 Vlast_coding_system_used = Qraw_text;
999 GlobalUnlock (htext);
1002 closeclip:
1003 CloseClipboard ();
1005 done:
1006 UNBLOCK_INPUT;
1008 return (ret);
1011 /* Support checking for a clipboard selection. */
1013 DEFUN ("x-selection-exists-p", Fx_selection_exists_p, Sx_selection_exists_p,
1014 0, 1, 0,
1015 doc: /* Whether there is an owner for the given X Selection.
1016 The arg should be the name of the selection in question, typically one of
1017 the symbols `PRIMARY', `SECONDARY', or `CLIPBOARD'.
1018 \(Those are literal upper-case symbol names, since that's what X expects.)
1019 For convenience, the symbol nil is the same as `PRIMARY',
1020 and t is the same as `SECONDARY'. */)
1021 (Lisp_Object selection)
1023 CHECK_SYMBOL (selection);
1025 /* Return nil for PRIMARY and SECONDARY selections; for CLIPBOARD, check
1026 if the clipboard currently has valid text format contents. */
1028 if (EQ (selection, QCLIPBOARD))
1030 Lisp_Object val = Qnil;
1032 setup_config ();
1034 if (OpenClipboard (NULL))
1036 UINT format = 0;
1037 while ((format = EnumClipboardFormats (format)))
1038 /* Check CF_TEXT in addition to cfg_clipboard_type,
1039 because we can fall back on that if CF_UNICODETEXT is
1040 not available. Actually a check for CF_TEXT only
1041 should be enough. */
1042 if (format == cfg_clipboard_type || format == CF_TEXT)
1044 val = Qt;
1045 break;
1047 CloseClipboard ();
1049 return val;
1051 return Qnil;
1054 /* One-time init. Called in the un-dumped Emacs, but not in the
1055 dumped version. */
1057 void
1058 syms_of_w32select (void)
1060 defsubr (&Sw32_set_clipboard_data);
1061 defsubr (&Sw32_get_clipboard_data);
1062 defsubr (&Sx_selection_exists_p);
1064 DEFVAR_LISP ("selection-coding-system", Vselection_coding_system,
1065 doc: /* Coding system for communicating with other programs.
1067 For MS-Windows and MS-DOS:
1068 When sending or receiving text via selection and clipboard, the text
1069 is encoded or decoded by this coding system. The default value is
1070 the current system default encoding on 9x/Me, `utf-16le-dos'
1071 \(Unicode) on NT/W2K/XP, and `iso-latin-1-dos' on MS-DOS.
1073 For X Windows:
1074 When sending text via selection and clipboard, if the target
1075 data-type matches with the type of this coding system, it is used
1076 for encoding the text. Otherwise (including the case that this
1077 variable is nil), a proper coding system is used as below:
1079 data-type coding system
1080 --------- -------------
1081 UTF8_STRING utf-8
1082 COMPOUND_TEXT compound-text-with-extensions
1083 STRING iso-latin-1
1084 C_STRING no-conversion
1086 When receiving text, if this coding system is non-nil, it is used
1087 for decoding regardless of the data-type. If this is nil, a
1088 proper coding system is used according to the data-type as above.
1090 See also the documentation of the variable `x-select-request-type' how
1091 to control which data-type to request for receiving text.
1093 The default value is nil. */);
1094 /* The actual value is set dynamically in the dumped Emacs, see
1095 below. */
1096 Vselection_coding_system = Qnil;
1098 DEFVAR_LISP ("next-selection-coding-system", Vnext_selection_coding_system,
1099 doc: /* Coding system for the next communication with other programs.
1100 Usually, `selection-coding-system' is used for communicating with
1101 other programs (X Windows clients or MS Windows programs). But, if this
1102 variable is set, it is used for the next communication only.
1103 After the communication, this variable is set to nil. */);
1104 Vnext_selection_coding_system = Qnil;
1106 DEFSYM (QCLIPBOARD, "CLIPBOARD");
1108 cfg_coding_system = Qnil; staticpro (&cfg_coding_system);
1109 current_text = Qnil; staticpro (&current_text);
1110 current_coding_system = Qnil; staticpro (&current_coding_system);
1112 DEFSYM (QUNICODE, "utf-16le-dos");
1113 QANSICP = Qnil; staticpro (&QANSICP);
1114 QOEMCP = Qnil; staticpro (&QOEMCP);
1117 /* One-time init. Called in the dumped Emacs, but not in the
1118 un-dumped version. */
1120 void
1121 globals_of_w32select (void)
1123 DEFAULT_LCID = GetUserDefaultLCID ();
1124 /* Drop the sort order from the LCID, so we can compare this with
1125 CF_LOCALE objects that have the same fix on 9x. */
1126 DEFAULT_LCID = MAKELCID (LANGIDFROMLCID (DEFAULT_LCID), SORT_DEFAULT);
1128 ANSICP = GetACP ();
1129 OEMCP = GetOEMCP ();
1131 QANSICP = coding_from_cp (ANSICP);
1132 QOEMCP = coding_from_cp (OEMCP);
1134 if (os_subtype == OS_NT)
1135 Vselection_coding_system = QUNICODE;
1136 else if (inhibit_window_system)
1137 Vselection_coding_system = QOEMCP;
1138 else
1139 Vselection_coding_system = QANSICP;
1141 clipboard_owner = create_owner ();