Implement cygw32
[emacs.git] / src / w32select.c
blob6b855b43a35349f70dc436fc611ab3844180829f
1 /* Selection processing for Emacs on the Microsoft Windows API.
3 Copyright (C) 1993-1994, 2001-2012 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* Written by Kevin Gallo, Benjamin Riefenstahl */
24 * Notes on usage of selection-coding-system and
25 * next-selection-coding-system on MS Windows:
27 * The selection coding system variables apply only to the version of
28 * the clipboard data that is closest in type, i.e. when a 16-bit
29 * Unicode coding system is given, they apply to he Unicode clipboard
30 * (CF_UNICODETEXT), when a well-known console codepage is given, they
31 * apply to the console version of the clipboard data (CF_OEMTEXT),
32 * else they apply to the normal 8-bit text clipboard (CF_TEXT).
34 * When pasting (getting data from the OS), the clipboard format that
35 * matches the {next-}selection-coding-system is retrieved. If
36 * Unicode is requested, but not available, 8-bit text (CF_TEXT) is
37 * used. In all other cases the OS will transparently convert
38 * formats, so no other fallback is needed.
40 * When copying or cutting (sending data to the OS), the data is
41 * announced and stored internally, but only actually rendered on
42 * request. The requestor determines the format provided. The
43 * {next-}selection-coding-system is only used, when its corresponding
44 * clipboard type matches the type requested.
46 * Scenarios to use the facilities for customizing the selection
47 * coding system are:
49 * ;; Generally use KOI8-R instead of the russian MS codepage for
50 * ;; the 8-bit clipboard.
51 * (set-selection-coding-system 'koi8-r-dos)
53 * Or
55 * ;; Create a special clipboard copy function that uses codepage
56 * ;; 1253 (Greek) to copy Greek text to a specific non-Unicode
57 * ;; application.
58 * (defun greek-copy (beg end)
59 * (interactive "r")
60 * (set-next-selection-coding-system 'cp1253-dos)
61 * (copy-region-as-kill beg end))
62 * (global-set-key "\C-c\C-c" 'greek-copy)
66 * Ideas for further directions:
68 * The encoding and decoding routines could be moved to Lisp code
69 * similar to how xselect.c does it (using well-known routine names
70 * for the delayed rendering). If the definition of which clipboard
71 * types should be supported is also moved to Lisp, functionality
72 * could be expanded to CF_HTML, CF_RTF and maybe other types.
75 #include <config.h>
76 #include <setjmp.h>
77 #include "lisp.h"
78 #include "w32term.h" /* for all of the w32 includes */
79 #include "w32heap.h" /* os_subtype */
80 #include "blockinput.h"
81 #include "charset.h"
82 #include "coding.h"
83 #include "composite.h"
85 #ifdef CYGWIN
86 #include <string.h>
87 #include <stdio.h>
88 #define _memccpy memccpy
89 #endif
91 static HGLOBAL convert_to_handle_as_ascii (void);
92 static HGLOBAL convert_to_handle_as_coded (Lisp_Object coding_system);
93 static Lisp_Object render (Lisp_Object oformat);
94 static Lisp_Object render_locale (void);
95 static Lisp_Object render_all (Lisp_Object ignore);
96 static void run_protected (Lisp_Object (*code) (Lisp_Object), Lisp_Object arg);
97 static Lisp_Object lisp_error_handler (Lisp_Object error);
98 static LRESULT CALLBACK owner_callback (HWND win, UINT msg,
99 WPARAM wp, LPARAM lp);
100 static HWND create_owner (void);
102 static void setup_config (void);
103 static BOOL WINAPI enum_locale_callback (/*const*/ char* loc_string);
104 static UINT cp_from_locale (LCID lcid, UINT format);
105 static Lisp_Object coding_from_cp (UINT codepage);
106 static Lisp_Object validate_coding_system (Lisp_Object coding_system);
107 static void setup_windows_coding_system (Lisp_Object coding_system,
108 struct coding_system * coding);
111 /* A remnant from X11: Symbol for the CLIPBORD selection type. Other
112 selections are not used on Windows, so we don't need symbols for
113 PRIMARY and SECONDARY. */
114 Lisp_Object QCLIPBOARD;
116 /* Internal pseudo-constants, initialized in globals_of_w32select()
117 based on current system parameters. */
118 static LCID DEFAULT_LCID;
119 static UINT ANSICP, OEMCP;
120 static Lisp_Object QUNICODE, QANSICP, QOEMCP;
122 /* A hidden window just for the clipboard management. */
123 static HWND clipboard_owner;
124 /* A flag to tell WM_DESTROYCLIPBOARD who is to blame this time (just
125 checking GetClipboardOwner() doesn't work, sadly). */
126 static int modifying_clipboard = 0;
128 /* Configured transfer parameters, based on the last inspection of
129 selection-coding-system. */
130 static Lisp_Object cfg_coding_system;
131 static UINT cfg_codepage;
132 static LCID cfg_lcid;
133 static UINT cfg_clipboard_type;
135 /* The current state for delayed rendering. */
136 static Lisp_Object current_text;
137 static Lisp_Object current_coding_system;
138 static int current_requires_encoding, current_num_nls;
139 static UINT current_clipboard_type;
140 static LCID current_lcid;
142 #if TRACE
143 #define ONTRACE(stmt) stmt
144 #else
145 #define ONTRACE(stmt) /*stmt*/
146 #endif
149 /* This function assumes that there is no multibyte character in
150 current_text, so we can short-cut encoding. */
152 static HGLOBAL
153 convert_to_handle_as_ascii (void)
155 HGLOBAL htext = NULL;
156 int nbytes;
157 int truelen;
158 unsigned char *src;
159 unsigned char *dst;
161 ONTRACE (fprintf (stderr, "convert_to_handle_as_ascii\n"));
163 nbytes = SBYTES (current_text) + 1;
164 src = SDATA (current_text);
166 /* We need to add to the size the number of LF chars where we have
167 to insert CR chars (the standard CF_TEXT clipboard format uses
168 CRLF line endings, while Emacs uses just LF internally). */
170 truelen = nbytes + current_num_nls;
172 if ((htext = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, truelen)) == NULL)
173 return NULL;
175 if ((dst = (unsigned char *) GlobalLock (htext)) == NULL)
177 GlobalFree (htext);
178 return NULL;
181 /* convert to CRLF line endings expected by clipboard */
182 while (1)
184 unsigned char *next;
185 /* copy next line or remaining bytes including '\0' */
186 next = _memccpy (dst, src, '\n', nbytes);
187 if (next)
189 /* copied one line ending with '\n' */
190 int copied = next - dst;
191 nbytes -= copied;
192 src += copied;
193 /* insert '\r' before '\n' */
194 next[-1] = '\r';
195 next[0] = '\n';
196 dst = next + 1;
198 else
199 /* copied remaining partial line -> now finished */
200 break;
203 GlobalUnlock (htext);
205 return htext;
208 /* This function assumes that there are multibyte or NUL characters in
209 current_text, or that we need to construct Unicode. It runs the
210 text through the encoding machinery. */
212 static HGLOBAL
213 convert_to_handle_as_coded (Lisp_Object coding_system)
215 HGLOBAL htext;
216 unsigned char *dst = NULL;
217 struct coding_system coding;
219 ONTRACE (fprintf (stderr, "convert_to_handle_as_coded: %s\n",
220 SDATA (SYMBOL_NAME (coding_system))));
222 setup_windows_coding_system (coding_system, &coding);
223 coding.dst_bytes = SBYTES (current_text) * 2;
224 coding.destination = xmalloc (coding.dst_bytes);
225 encode_coding_object (&coding, current_text, 0, 0,
226 SCHARS (current_text), SBYTES (current_text), Qnil);
228 htext = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, coding.produced +2);
230 if (htext != NULL)
231 dst = (unsigned char *) GlobalLock (htext);
233 if (dst != NULL)
235 memcpy (dst, coding.destination, coding.produced);
236 /* Add the string terminator. Add two NULs in case we are
237 producing Unicode here. */
238 dst[coding.produced] = dst[coding.produced+1] = '\0';
240 GlobalUnlock (htext);
243 xfree (coding.destination);
245 return htext;
248 static Lisp_Object
249 render (Lisp_Object oformat)
251 HGLOBAL htext = NULL;
252 UINT format = XFASTINT (oformat);
254 ONTRACE (fprintf (stderr, "render\n"));
256 if (NILP (current_text))
257 return Qnil;
259 if (current_requires_encoding || format == CF_UNICODETEXT)
261 if (format == current_clipboard_type)
262 htext = convert_to_handle_as_coded (current_coding_system);
263 else
264 switch (format)
266 case CF_UNICODETEXT:
267 htext = convert_to_handle_as_coded (QUNICODE);
268 break;
269 case CF_TEXT:
270 case CF_OEMTEXT:
272 Lisp_Object cs;
273 cs = coding_from_cp (cp_from_locale (current_lcid, format));
274 htext = convert_to_handle_as_coded (cs);
275 break;
279 else
280 htext = convert_to_handle_as_ascii ();
282 ONTRACE (fprintf (stderr, "render: htext = 0x%08X\n", (unsigned) htext));
284 if (htext == NULL)
285 return Qnil;
287 if (SetClipboardData (format, htext) == NULL)
289 GlobalFree (htext);
290 return Qnil;
293 return Qt;
296 static Lisp_Object
297 render_locale (void)
299 HANDLE hlocale = NULL;
300 LCID * lcid_ptr;
302 ONTRACE (fprintf (stderr, "render_locale\n"));
304 if (current_lcid == LOCALE_NEUTRAL || current_lcid == DEFAULT_LCID)
305 return Qt;
307 hlocale = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, sizeof (current_lcid));
308 if (hlocale == NULL)
309 return Qnil;
311 if ((lcid_ptr = (LCID *) GlobalLock (hlocale)) == NULL)
313 GlobalFree (hlocale);
314 return Qnil;
317 *lcid_ptr = current_lcid;
318 GlobalUnlock (hlocale);
320 if (SetClipboardData (CF_LOCALE, hlocale) == NULL)
322 GlobalFree (hlocale);
323 return Qnil;
326 return Qt;
329 /* At the end of the program, we want to ensure that our clipboard
330 data survives us. This code will do that. */
332 static Lisp_Object
333 render_all (Lisp_Object ignore)
335 ONTRACE (fprintf (stderr, "render_all\n"));
337 /* According to the docs we should not call OpenClipboard() here,
338 but testing on W2K and working code in other projects shows that
339 it is actually necessary. */
341 OpenClipboard (NULL);
343 /* There is no useful means to report errors here, there are none
344 expected anyway, and even if there were errors, they wouldn't do
345 any harm. So we just go ahead and do what has to be done without
346 bothering with error handling. */
348 ++modifying_clipboard;
349 EmptyClipboard ();
350 --modifying_clipboard;
352 /* For text formats that we don't render here, the OS can use its
353 own translation rules instead, so we don't really need to offer
354 everything. To minimize memory consumption we cover three
355 possible situations based on our primary format as detected from
356 selection-coding-system (see setup_config()):
358 - Post CF_TEXT only. Let the OS convert to CF_OEMTEXT and the OS
359 (on NT) or the application (on 9x/Me) convert to
360 CF_UNICODETEXT.
362 - Post CF_OEMTEXT only. Similar automatic conversions happen as
363 for CF_TEXT.
365 - Post CF_UNICODETEXT + CF_TEXT. 9x itself ignores
366 CF_UNICODETEXT, even though some applications can still handle
369 Note 1: We render the less capable CF_TEXT *before* the more
370 capable CF_UNICODETEXT, to prevent clobbering through automatic
371 conversions, just in case.
373 Note 2: We could check os_subtype here and only render the
374 additional CF_TEXT on 9x/Me. But OTOH with
375 current_clipboard_type == CF_UNICODETEXT we don't involve the
376 automatic conversions anywhere else, so to get consistent
377 results, we probably don't want to rely on it here either. */
379 render_locale ();
381 if (current_clipboard_type == CF_UNICODETEXT)
382 render (make_number (CF_TEXT));
383 render (make_number (current_clipboard_type));
385 CloseClipboard ();
387 return Qnil;
390 static void
391 run_protected (Lisp_Object (*code) (Lisp_Object), Lisp_Object arg)
393 /* FIXME: This works but it doesn't feel right. Too much fiddling
394 with global variables and calling strange looking functions. Is
395 this really the right way to run Lisp callbacks? */
397 extern int waiting_for_input; /* from keyboard.c */
398 int owfi;
400 BLOCK_INPUT;
402 /* Fsignal calls abort() if it sees that waiting_for_input is
403 set. */
404 owfi = waiting_for_input;
405 waiting_for_input = 0;
407 internal_condition_case_1 (code, arg, Qt, lisp_error_handler);
409 waiting_for_input = owfi;
411 UNBLOCK_INPUT;
414 static Lisp_Object
415 lisp_error_handler (Lisp_Object error)
417 Vsignaling_function = Qnil;
418 cmd_error_internal (error, "Error in delayed clipboard rendering: ");
419 Vinhibit_quit = Qt;
420 return Qt;
424 static LRESULT CALLBACK
425 owner_callback (HWND win, UINT msg, WPARAM wp, LPARAM lp)
427 switch (msg)
429 case WM_RENDERFORMAT:
430 ONTRACE (fprintf (stderr, "WM_RENDERFORMAT\n"));
431 run_protected (render, make_number (wp));
432 return 0;
434 case WM_RENDERALLFORMATS:
435 ONTRACE (fprintf (stderr, "WM_RENDERALLFORMATS\n"));
436 run_protected (render_all, Qnil);
437 return 0;
439 case WM_DESTROYCLIPBOARD:
440 if (!modifying_clipboard)
442 ONTRACE (fprintf (stderr, "WM_DESTROYCLIPBOARD (other)\n"));
443 current_text = Qnil;
444 current_coding_system = Qnil;
446 else
448 ONTRACE (fprintf (stderr, "WM_DESTROYCLIPBOARD (self)\n"));
450 return 0;
452 case WM_DESTROY:
453 if (win == clipboard_owner)
454 clipboard_owner = NULL;
455 break;
458 return DefWindowProc (win, msg, wp, lp);
461 static HWND
462 create_owner (void)
464 static const char CLASSNAME[] = "Emacs Clipboard";
465 WNDCLASS wc;
467 memset (&wc, 0, sizeof (wc));
468 wc.lpszClassName = CLASSNAME;
469 wc.lpfnWndProc = owner_callback;
470 RegisterClass (&wc);
472 return CreateWindow (CLASSNAME, CLASSNAME, 0, 0, 0, 0, 0, NULL, NULL,
473 NULL, NULL);
476 /* Called on exit by term_ntproc() in w32.c */
478 void
479 term_w32select (void)
481 /* This is needed to trigger WM_RENDERALLFORMATS. */
482 if (clipboard_owner != NULL)
483 DestroyWindow (clipboard_owner);
486 static void
487 setup_config (void)
489 const char *coding_name;
490 const char *cp;
491 char *end;
492 int slen;
493 Lisp_Object coding_system;
494 Lisp_Object dos_coding_system;
496 CHECK_SYMBOL (Vselection_coding_system);
498 coding_system = NILP (Vnext_selection_coding_system) ?
499 Vselection_coding_system : Vnext_selection_coding_system;
501 dos_coding_system = validate_coding_system (coding_system);
502 if (NILP (dos_coding_system))
503 Fsignal (Qerror,
504 list2 (build_string ("Coding system is invalid or doesn't have "
505 "an eol variant for dos line ends"),
506 coding_system));
508 /* Check if we have it cached */
509 if (!NILP (cfg_coding_system)
510 && EQ (cfg_coding_system, dos_coding_system))
511 return;
512 cfg_coding_system = dos_coding_system;
514 /* Set some sensible fallbacks */
515 cfg_codepage = ANSICP;
516 cfg_lcid = LOCALE_NEUTRAL;
517 cfg_clipboard_type = CF_TEXT;
519 /* Interpret the coding system symbol name */
520 coding_name = SDATA (SYMBOL_NAME (cfg_coding_system));
522 /* "(.*-)?utf-16.*" -> CF_UNICODETEXT */
523 cp = strstr (coding_name, "utf-16");
524 if (cp != NULL && (cp == coding_name || cp[-1] == '-'))
526 cfg_clipboard_type = CF_UNICODETEXT;
527 return;
530 /* "cp[0-9]+.*" or "windows-[0-9]+.*" -> CF_TEXT or CF_OEMTEXT */
531 slen = strlen (coding_name);
532 if (slen >= 4 && coding_name[0] == 'c' && coding_name[1] == 'p')
533 cp = coding_name + 2;
534 else if (slen >= 10 && memcmp (coding_name, "windows-", 8) == 0)
535 cp = coding_name + 8;
536 else
537 return;
539 end = (char*)cp;
540 cfg_codepage = strtol (cp, &end, 10);
542 /* Error return from strtol() or number of digits < 2 -> Restore the
543 default and drop it. */
544 if (cfg_codepage == 0 || (end-cp) < 2 )
546 cfg_codepage = ANSICP;
547 return;
550 /* Is it the currently active system default? */
551 if (cfg_codepage == ANSICP)
553 /* cfg_clipboard_type = CF_TEXT; */
554 return;
556 if (cfg_codepage == OEMCP)
558 cfg_clipboard_type = CF_OEMTEXT;
559 return;
562 /* Else determine a suitable locale the hard way. */
563 EnumSystemLocales (enum_locale_callback, LCID_INSTALLED);
566 static BOOL WINAPI
567 enum_locale_callback (/*const*/ char* loc_string)
569 LCID lcid;
570 UINT codepage;
572 lcid = strtoul (loc_string, NULL, 16);
574 /* Is the wanted codepage the "ANSI" codepage for this locale? */
575 codepage = cp_from_locale (lcid, CF_TEXT);
576 if (codepage == cfg_codepage)
578 cfg_lcid = lcid;
579 cfg_clipboard_type = CF_TEXT;
580 return FALSE; /* Stop enumeration */
583 /* Is the wanted codepage the OEM codepage for this locale? */
584 codepage = cp_from_locale (lcid, CF_OEMTEXT);
585 if (codepage == cfg_codepage)
587 cfg_lcid = lcid;
588 cfg_clipboard_type = CF_OEMTEXT;
589 return FALSE; /* Stop enumeration */
592 return TRUE; /* Continue enumeration */
595 static UINT
596 cp_from_locale (LCID lcid, UINT format)
598 char buffer[20] = "";
599 UINT variant, cp;
601 variant =
602 format == CF_TEXT ? LOCALE_IDEFAULTANSICODEPAGE : LOCALE_IDEFAULTCODEPAGE;
604 GetLocaleInfo (lcid, variant, buffer, sizeof (buffer));
605 cp = strtoul (buffer, NULL, 10);
607 if (cp == CP_ACP)
608 return ANSICP;
609 else if (cp == CP_OEMCP)
610 return OEMCP;
611 else
612 return cp;
615 static Lisp_Object
616 coding_from_cp (UINT codepage)
618 char buffer[30];
619 sprintf (buffer, "cp%d-dos", (int) codepage);
620 return intern (buffer);
621 /* We don't need to check that this coding system actually exists
622 right here, because that is done later for all coding systems
623 used, regardless of where they originate. */
626 static Lisp_Object
627 validate_coding_system (Lisp_Object coding_system)
629 Lisp_Object eol_type;
631 /* Make sure the input is valid. */
632 if (NILP (Fcoding_system_p (coding_system)))
633 return Qnil;
635 /* Make sure we use a DOS coding system as mandated by the system
636 specs. */
637 eol_type = Fcoding_system_eol_type (coding_system);
639 /* Already a DOS coding system? */
640 if (EQ (eol_type, make_number (1)))
641 return coding_system;
643 /* Get EOL_TYPE vector of the base of CODING_SYSTEM. */
644 if (!VECTORP (eol_type))
646 eol_type = Fcoding_system_eol_type (Fcoding_system_base (coding_system));
647 if (!VECTORP (eol_type))
648 return Qnil;
651 return AREF (eol_type, 1);
654 static void
655 setup_windows_coding_system (Lisp_Object coding_system,
656 struct coding_system * coding)
658 memset (coding, 0, sizeof (*coding));
659 setup_coding_system (coding_system, coding);
661 /* Unset CODING_ANNOTATE_COMPOSITION_MASK. Previous code had
662 comments about crashes in encode_coding_iso2022 trying to
663 dereference a null pointer when composition was on. Selection
664 data should not contain any composition sequence on Windows.
666 CODING_ANNOTATION_MASK also includes
667 CODING_ANNOTATE_DIRECTION_MASK and CODING_ANNOTATE_CHARSET_MASK,
668 which both apply to ISO6429 only. We don't know if these really
669 need to be unset on Windows, but it probably doesn't hurt
670 either. */
671 coding->mode &= ~CODING_ANNOTATION_MASK;
672 coding->mode |= CODING_MODE_LAST_BLOCK | CODING_MODE_SAFE_ENCODING;
677 DEFUN ("w32-set-clipboard-data", Fw32_set_clipboard_data,
678 Sw32_set_clipboard_data, 1, 2, 0,
679 doc: /* This sets the clipboard data to the given text. */)
680 (Lisp_Object string, Lisp_Object ignored)
682 BOOL ok = TRUE;
683 int nbytes;
684 unsigned char *src;
685 unsigned char *dst;
686 unsigned char *end;
688 /* This parameter used to be the current frame, but we don't use
689 that any more. */
690 (void) ignored;
692 CHECK_STRING (string);
694 setup_config ();
696 current_text = string;
697 current_coding_system = cfg_coding_system;
698 current_clipboard_type = cfg_clipboard_type;
699 current_lcid = cfg_lcid;
700 current_num_nls = 0;
701 current_requires_encoding = 0;
703 BLOCK_INPUT;
705 /* Check for non-ASCII characters. While we are at it, count the
706 number of LFs, so we know how many CRs we will have to add later
707 (just in the case where we can use our internal ASCII rendering,
708 see code and comment in convert_to_handle_as_ascii() above). */
709 nbytes = SBYTES (string);
710 src = SDATA (string);
712 for (dst = src, end = src+nbytes; dst < end; dst++)
714 if (*dst == '\n')
715 current_num_nls++;
716 else if (*dst >= 0x80 || *dst == 0)
718 current_requires_encoding = 1;
719 break;
723 if (!current_requires_encoding)
725 /* If all we have is ASCII we don't need to pretend we offer
726 anything fancy. */
727 current_coding_system = Qraw_text;
728 current_clipboard_type = CF_TEXT;
729 current_lcid = LOCALE_NEUTRAL;
732 if (!OpenClipboard (clipboard_owner))
733 goto error;
735 ++modifying_clipboard;
736 ok = EmptyClipboard ();
737 --modifying_clipboard;
739 /* If we have something non-ASCII we may want to set a locale. We
740 do that directly (non-delayed), as it's just a small bit. */
741 if (ok)
742 ok = !NILP (render_locale ());
744 if (ok)
746 if (clipboard_owner == NULL)
748 /* If for some reason we don't have a clipboard_owner, we
749 just set the text format as chosen by the configuration
750 and than forget about the whole thing. */
751 ok = !NILP (render (make_number (current_clipboard_type)));
752 current_text = Qnil;
753 current_coding_system = Qnil;
755 else
757 /* Advertise all supported formats so that whatever the
758 requestor chooses, only one encoding step needs to be
759 made. This is intentionally different from what we do in
760 the handler for WM_RENDERALLFORMATS. */
761 SetClipboardData (CF_UNICODETEXT, NULL);
762 SetClipboardData (CF_TEXT, NULL);
763 SetClipboardData (CF_OEMTEXT, NULL);
767 CloseClipboard ();
769 /* With delayed rendering we haven't really "used" this coding
770 system yet, and it's even unclear if we ever will. But this is a
771 way to tell the upper level what we *would* use under ideal
772 circumstances.
774 We don't signal the actually used coding-system later when we
775 finally render, because that can happen at any time and we don't
776 want to disturb the "foreground" action. */
777 if (ok)
778 Vlast_coding_system_used = current_coding_system;
780 Vnext_selection_coding_system = Qnil;
782 if (ok) goto done;
784 error:
786 ok = FALSE;
787 current_text = Qnil;
788 current_coding_system = Qnil;
790 done:
791 UNBLOCK_INPUT;
793 return (ok ? string : Qnil);
797 DEFUN ("w32-get-clipboard-data", Fw32_get_clipboard_data,
798 Sw32_get_clipboard_data, 0, 1, 0,
799 doc: /* This gets the clipboard data in text format. */)
800 (Lisp_Object ignored)
802 HGLOBAL htext;
803 Lisp_Object ret = Qnil;
804 UINT actual_clipboard_type;
805 int use_configured_coding_system = 1;
807 /* This parameter used to be the current frame, but we don't use
808 that any more. */
809 (void) ignored;
811 /* Don't pass our own text from the clipboard (which might be
812 troublesome if the killed text includes null characters). */
813 if (!NILP (current_text))
814 return ret;
816 setup_config ();
817 actual_clipboard_type = cfg_clipboard_type;
819 BLOCK_INPUT;
821 if (!OpenClipboard (clipboard_owner))
822 goto done;
824 if ((htext = GetClipboardData (actual_clipboard_type)) == NULL)
826 /* If we want CF_UNICODETEXT but can't get it, the current
827 coding system is useless. OTOH we can still try and decode
828 CF_TEXT based on the locale that the system gives us and that
829 we get down below. */
830 if (actual_clipboard_type == CF_UNICODETEXT)
832 htext = GetClipboardData (CF_TEXT);
833 if (htext != NULL)
835 actual_clipboard_type = CF_TEXT;
836 use_configured_coding_system = 0;
840 if (htext == NULL)
841 goto closeclip;
844 unsigned char *src;
845 unsigned char *dst;
846 int nbytes;
847 int truelen;
848 int require_decoding = 0;
850 if ((src = (unsigned char *) GlobalLock (htext)) == NULL)
851 goto closeclip;
853 /* If the clipboard data contains any non-ascii code, we need to
854 decode it with a coding system. */
855 if (actual_clipboard_type == CF_UNICODETEXT)
857 nbytes = lstrlenW ((WCHAR *)src) * 2;
858 require_decoding = 1;
860 else
862 int i;
864 nbytes = strlen (src);
866 for (i = 0; i < nbytes; i++)
868 if (src[i] >= 0x80)
870 require_decoding = 1;
871 break;
876 if (require_decoding)
878 struct coding_system coding;
879 Lisp_Object coding_system = Qnil;
880 Lisp_Object dos_coding_system;
882 /* `next-selection-coding-system' should override everything,
883 even when the locale passed by the system disagrees. The
884 only exception is when `next-selection-coding-system'
885 requested CF_UNICODETEXT and we couldn't get that. */
886 if (use_configured_coding_system
887 && !NILP (Vnext_selection_coding_system))
888 coding_system = Vnext_selection_coding_system;
890 /* If we have CF_TEXT or CF_OEMTEXT, we want to check out
891 CF_LOCALE, too. */
892 else if (actual_clipboard_type != CF_UNICODETEXT)
894 HGLOBAL hlocale;
895 LCID lcid = DEFAULT_LCID;
896 UINT cp;
898 /* Documentation says that the OS always generates
899 CF_LOCALE info automatically, so the locale handle
900 should always be present. Fact is that this is not
901 always true on 9x ;-(. */
902 hlocale = GetClipboardData (CF_LOCALE);
903 if (hlocale != NULL)
905 const LCID * lcid_ptr;
906 lcid_ptr = (const LCID *) GlobalLock (hlocale);
907 if (lcid_ptr != NULL)
909 lcid = *lcid_ptr;
910 GlobalUnlock (hlocale);
913 /* 9x has garbage as the sort order (to be exact there
914 is another instance of the language id in the upper
915 word). We don't care about sort order anyway, so
916 we just filter out the unneeded mis-information to
917 avoid irritations. */
918 lcid = MAKELCID (LANGIDFROMLCID (lcid), SORT_DEFAULT);
921 /* If we are using fallback from CF_UNICODETEXT, we can't
922 use the configured coding system. Also we don't want
923 to use it, if the system has supplied us with a locale
924 and it is not just the system default. */
925 if (!use_configured_coding_system || lcid != DEFAULT_LCID)
927 cp = cp_from_locale (lcid, actual_clipboard_type);
928 /* If it's just our current standard setting anyway,
929 use the coding system that the user has selected.
930 Otherwise create a new spec to match the locale
931 that was specified by the other side or the
932 system. */
933 if (!use_configured_coding_system || cp != cfg_codepage)
934 coding_system = coding_from_cp (cp);
938 if (NILP (coding_system))
939 coding_system = Vselection_coding_system;
940 Vnext_selection_coding_system = Qnil;
942 dos_coding_system = validate_coding_system (coding_system);
943 if (!NILP (dos_coding_system))
945 setup_windows_coding_system (dos_coding_system, &coding);
946 coding.source = src;
947 decode_coding_object (&coding, Qnil, 0, 0, nbytes, nbytes, Qt);
948 ret = coding.dst_object;
950 Vlast_coding_system_used = CODING_ID_NAME (coding.id);
953 else
955 /* FIXME: We may want to repeat the code in this branch for
956 the Unicode case. */
958 /* Need to know final size after CR chars are removed because
959 we can't change the string size manually, and doing an
960 extra copy is silly. We only remove CR when it appears as
961 part of CRLF. */
963 truelen = nbytes;
964 dst = src;
965 /* avoid using strchr because it recomputes the length everytime */
966 while ((dst = memchr (dst, '\r', nbytes - (dst - src))) != NULL)
968 if (dst[1] == '\n') /* safe because of trailing '\0' */
969 truelen--;
970 dst++;
973 ret = make_uninit_string (truelen);
975 /* Convert CRLF line endings (the standard CF_TEXT clipboard
976 format) to LF endings as used internally by Emacs. */
978 dst = SDATA (ret);
979 while (1)
981 unsigned char *next;
982 /* copy next line or remaining bytes excluding '\0' */
983 next = _memccpy (dst, src, '\r', nbytes);
984 if (next)
986 /* copied one line ending with '\r' */
987 int copied = next - dst;
988 nbytes -= copied;
989 dst += copied;
990 src += copied;
991 if (*src == '\n')
992 dst--; /* overwrite '\r' with '\n' */
994 else
995 /* copied remaining partial line -> now finished */
996 break;
999 Vlast_coding_system_used = Qraw_text;
1002 GlobalUnlock (htext);
1005 closeclip:
1006 CloseClipboard ();
1008 done:
1009 UNBLOCK_INPUT;
1011 return (ret);
1014 /* Support checking for a clipboard selection. */
1016 DEFUN ("x-selection-exists-p", Fx_selection_exists_p, Sx_selection_exists_p,
1017 0, 2, 0,
1018 doc: /* Whether there is an owner for the given X selection.
1019 SELECTION should be the name of the selection in question, typically
1020 one of the symbols `PRIMARY', `SECONDARY', or `CLIPBOARD'. (X expects
1021 these literal upper-case names.) The symbol nil is the same as
1022 `PRIMARY', and t is the same as `SECONDARY'.
1024 TERMINAL should be a terminal object or a frame specifying the X
1025 server to query. If omitted or nil, that stands for the selected
1026 frame's display, or the first available X display. */)
1027 (Lisp_Object selection, Lisp_Object terminal)
1029 CHECK_SYMBOL (selection);
1031 /* Return nil for PRIMARY and SECONDARY selections; for CLIPBOARD, check
1032 if the clipboard currently has valid text format contents. */
1034 if (EQ (selection, QCLIPBOARD))
1036 Lisp_Object val = Qnil;
1038 setup_config ();
1040 if (OpenClipboard (NULL))
1042 UINT format = 0;
1043 while ((format = EnumClipboardFormats (format)))
1044 /* Check CF_TEXT in addition to cfg_clipboard_type,
1045 because we can fall back on that if CF_UNICODETEXT is
1046 not available. Actually a check for CF_TEXT only
1047 should be enough. */
1048 if (format == cfg_clipboard_type || format == CF_TEXT)
1050 val = Qt;
1051 break;
1053 CloseClipboard ();
1055 return val;
1057 return Qnil;
1060 /* One-time init. Called in the un-dumped Emacs, but not in the
1061 dumped version. */
1063 void
1064 syms_of_w32select (void)
1066 defsubr (&Sw32_set_clipboard_data);
1067 defsubr (&Sw32_get_clipboard_data);
1068 defsubr (&Sx_selection_exists_p);
1070 DEFVAR_LISP ("selection-coding-system", Vselection_coding_system,
1071 doc: /* Coding system for communicating with other programs.
1073 For MS-Windows and MS-DOS:
1074 When sending or receiving text via selection and clipboard, the text
1075 is encoded or decoded by this coding system. The default value is
1076 the current system default encoding on 9x/Me, `utf-16le-dos'
1077 \(Unicode) on NT/W2K/XP, and `iso-latin-1-dos' on MS-DOS.
1079 For X Windows:
1080 When sending text via selection and clipboard, if the target
1081 data-type matches with the type of this coding system, it is used
1082 for encoding the text. Otherwise (including the case that this
1083 variable is nil), a proper coding system is used as below:
1085 data-type coding system
1086 --------- -------------
1087 UTF8_STRING utf-8
1088 COMPOUND_TEXT compound-text-with-extensions
1089 STRING iso-latin-1
1090 C_STRING no-conversion
1092 When receiving text, if this coding system is non-nil, it is used
1093 for decoding regardless of the data-type. If this is nil, a
1094 proper coding system is used according to the data-type as above.
1096 See also the documentation of the variable `x-select-request-type' how
1097 to control which data-type to request for receiving text.
1099 The default value is nil. */);
1100 /* The actual value is set dynamically in the dumped Emacs, see
1101 below. */
1102 Vselection_coding_system = Qnil;
1104 DEFVAR_LISP ("next-selection-coding-system", Vnext_selection_coding_system,
1105 doc: /* Coding system for the next communication with other programs.
1106 Usually, `selection-coding-system' is used for communicating with
1107 other programs (X Windows clients or MS Windows programs). But, if this
1108 variable is set, it is used for the next communication only.
1109 After the communication, this variable is set to nil. */);
1110 Vnext_selection_coding_system = Qnil;
1112 DEFSYM (QCLIPBOARD, "CLIPBOARD");
1114 cfg_coding_system = Qnil; staticpro (&cfg_coding_system);
1115 current_text = Qnil; staticpro (&current_text);
1116 current_coding_system = Qnil; staticpro (&current_coding_system);
1118 DEFSYM (QUNICODE, "utf-16le-dos");
1119 QANSICP = Qnil; staticpro (&QANSICP);
1120 QOEMCP = Qnil; staticpro (&QOEMCP);
1123 /* One-time init. Called in the dumped Emacs, but not in the
1124 un-dumped version. */
1126 void
1127 globals_of_w32select (void)
1129 DEFAULT_LCID = GetUserDefaultLCID ();
1130 /* Drop the sort order from the LCID, so we can compare this with
1131 CF_LOCALE objects that have the same fix on 9x. */
1132 DEFAULT_LCID = MAKELCID (LANGIDFROMLCID (DEFAULT_LCID), SORT_DEFAULT);
1134 ANSICP = GetACP ();
1135 OEMCP = GetOEMCP ();
1137 QANSICP = coding_from_cp (ANSICP);
1138 QOEMCP = coding_from_cp (OEMCP);
1140 if (os_subtype == OS_NT)
1141 Vselection_coding_system = QUNICODE;
1142 else if (inhibit_window_system)
1143 Vselection_coding_system = QOEMCP;
1144 else
1145 Vselection_coding_system = QANSICP;
1147 clipboard_owner = create_owner ();