Rename option to shell-command-dont-erase-buffer
[emacs.git] / src / w32select.c
bloba38a42ca05097b80b9e66d3b8433596d75ee1e78
1 /* Selection processing for Emacs on the Microsoft Windows API.
3 Copyright (C) 1993-1994, 2001-2016 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 (at
10 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 "lisp.h"
77 #include "w32common.h" /* os_subtype */
78 #include "w32term.h" /* for all of the w32 includes */
79 #include "w32select.h"
80 #include "keyboard.h" /* for waiting_for_input */
81 #include "blockinput.h"
82 #include "coding.h"
84 #ifdef CYGWIN
85 #include <string.h>
86 #include <stdio.h>
87 #define _memccpy memccpy
88 #endif
90 static HGLOBAL convert_to_handle_as_ascii (void);
91 static HGLOBAL convert_to_handle_as_coded (Lisp_Object coding_system);
92 static Lisp_Object render (Lisp_Object oformat);
93 static Lisp_Object render_locale (void);
94 static Lisp_Object render_all (Lisp_Object ignore);
95 static void run_protected (Lisp_Object (*code) (Lisp_Object), Lisp_Object arg);
96 static Lisp_Object lisp_error_handler (Lisp_Object error);
97 static LRESULT CALLBACK ALIGN_STACK owner_callback (HWND win, UINT msg,
98 WPARAM wp, LPARAM lp);
99 static HWND create_owner (void);
101 static void setup_config (void);
102 static BOOL WINAPI enum_locale_callback (/*const*/ char* loc_string);
103 static UINT cp_from_locale (LCID lcid, UINT format);
104 static Lisp_Object coding_from_cp (UINT codepage);
105 static Lisp_Object validate_coding_system (Lisp_Object coding_system);
106 static void setup_windows_coding_system (Lisp_Object coding_system,
107 struct coding_system * coding);
109 /* Internal pseudo-constants, initialized in globals_of_w32select()
110 based on current system parameters. */
111 static LCID DEFAULT_LCID;
112 static UINT ANSICP, OEMCP;
113 static Lisp_Object QANSICP, QOEMCP;
115 /* A hidden window just for the clipboard management. */
116 static HWND clipboard_owner;
117 /* A flag to tell WM_DESTROYCLIPBOARD who is to blame this time (just
118 checking GetClipboardOwner() doesn't work, sadly). */
119 static int modifying_clipboard = 0;
121 /* Configured transfer parameters, based on the last inspection of
122 selection-coding-system. */
123 static Lisp_Object cfg_coding_system;
124 static UINT cfg_codepage;
125 static LCID cfg_lcid;
126 static UINT cfg_clipboard_type;
128 /* The current state for delayed rendering. */
129 static Lisp_Object current_text;
130 static Lisp_Object current_coding_system;
131 static int current_requires_encoding, current_num_nls;
132 static UINT current_clipboard_type;
133 static LCID current_lcid;
135 #if TRACE
136 #define ONTRACE(stmt) stmt
137 #else
138 #define ONTRACE(stmt) /*stmt*/
139 #endif
142 /* This function assumes that there is no multibyte character in
143 current_text, so we can short-cut encoding. */
145 static HGLOBAL
146 convert_to_handle_as_ascii (void)
148 HGLOBAL htext = NULL;
149 int nbytes;
150 int truelen;
151 unsigned char *src;
152 unsigned char *dst;
154 ONTRACE (fprintf (stderr, "convert_to_handle_as_ascii\n"));
156 nbytes = SBYTES (current_text) + 1;
157 src = SDATA (current_text);
159 /* We need to add to the size the number of LF chars where we have
160 to insert CR chars (the standard CF_TEXT clipboard format uses
161 CRLF line endings, while Emacs uses just LF internally). */
163 truelen = nbytes + current_num_nls;
165 if ((htext = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, truelen)) == NULL)
166 return NULL;
168 if ((dst = (unsigned char *) GlobalLock (htext)) == NULL)
170 GlobalFree (htext);
171 return NULL;
174 /* convert to CRLF line endings expected by clipboard */
175 while (1)
177 unsigned char *next;
178 /* copy next line or remaining bytes including '\0' */
179 next = _memccpy (dst, src, '\n', nbytes);
180 if (next)
182 /* copied one line ending with '\n' */
183 int copied = next - dst;
184 nbytes -= copied;
185 src += copied;
186 /* insert '\r' before '\n' */
187 next[-1] = '\r';
188 next[0] = '\n';
189 dst = next + 1;
191 else
192 /* copied remaining partial line -> now finished */
193 break;
196 GlobalUnlock (htext);
198 return htext;
201 /* This function assumes that there are multibyte or NUL characters in
202 current_text, or that we need to construct Unicode. It runs the
203 text through the encoding machinery. */
205 static HGLOBAL
206 convert_to_handle_as_coded (Lisp_Object coding_system)
208 HGLOBAL htext;
209 unsigned char *dst = NULL;
210 struct coding_system coding;
212 ONTRACE (fprintf (stderr, "convert_to_handle_as_coded: %s\n",
213 SDATA (SYMBOL_NAME (coding_system))));
215 setup_windows_coding_system (coding_system, &coding);
216 coding.dst_bytes = SBYTES (current_text) * 2;
217 coding.destination = xmalloc (coding.dst_bytes);
218 encode_coding_object (&coding, current_text, 0, 0,
219 SCHARS (current_text), SBYTES (current_text), Qnil);
221 htext = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, coding.produced +2);
223 if (htext != NULL)
224 dst = (unsigned char *) GlobalLock (htext);
226 if (dst != NULL)
228 memcpy (dst, coding.destination, coding.produced);
229 /* Add the string terminator. Add two NULs in case we are
230 producing Unicode here. */
231 dst[coding.produced] = dst[coding.produced+1] = '\0';
233 GlobalUnlock (htext);
236 xfree (coding.destination);
238 return htext;
241 static Lisp_Object
242 render (Lisp_Object oformat)
244 HGLOBAL htext = NULL;
245 UINT format = XFASTINT (oformat);
247 ONTRACE (fprintf (stderr, "render\n"));
249 if (NILP (current_text))
250 return Qnil;
252 if (current_requires_encoding || format == CF_UNICODETEXT)
254 if (format == current_clipboard_type)
255 htext = convert_to_handle_as_coded (current_coding_system);
256 else
257 switch (format)
259 case CF_UNICODETEXT:
260 htext = convert_to_handle_as_coded (Qutf_16le_dos);
261 break;
262 case CF_TEXT:
263 case CF_OEMTEXT:
265 Lisp_Object cs;
266 cs = coding_from_cp (cp_from_locale (current_lcid, format));
267 htext = convert_to_handle_as_coded (cs);
268 break;
272 else
273 htext = convert_to_handle_as_ascii ();
275 ONTRACE (fprintf (stderr, "render: htext = 0x%08X\n", (unsigned) htext));
277 if (htext == NULL)
278 return Qnil;
280 if (SetClipboardData (format, htext) == NULL)
282 GlobalFree (htext);
283 return Qnil;
286 return Qt;
289 static Lisp_Object
290 render_locale (void)
292 HANDLE hlocale = NULL;
293 LCID * lcid_ptr;
295 ONTRACE (fprintf (stderr, "render_locale\n"));
297 if (current_lcid == LOCALE_NEUTRAL || current_lcid == DEFAULT_LCID)
298 return Qt;
300 hlocale = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, sizeof (current_lcid));
301 if (hlocale == NULL)
302 return Qnil;
304 if ((lcid_ptr = (LCID *) GlobalLock (hlocale)) == NULL)
306 GlobalFree (hlocale);
307 return Qnil;
310 *lcid_ptr = current_lcid;
311 GlobalUnlock (hlocale);
313 if (SetClipboardData (CF_LOCALE, hlocale) == NULL)
315 GlobalFree (hlocale);
316 return Qnil;
319 return Qt;
322 /* At the end of the program, we want to ensure that our clipboard
323 data survives us. This code will do that. */
325 static Lisp_Object
326 render_all (Lisp_Object ignore)
328 ONTRACE (fprintf (stderr, "render_all\n"));
330 /* According to the docs we should not call OpenClipboard() here,
331 but testing on W2K and working code in other projects shows that
332 it is actually necessary. */
334 OpenClipboard (NULL);
336 /* There is no useful means to report errors here, there are none
337 expected anyway, and even if there were errors, they wouldn't do
338 any harm. So we just go ahead and do what has to be done without
339 bothering with error handling. */
341 ++modifying_clipboard;
342 EmptyClipboard ();
343 --modifying_clipboard;
345 /* For text formats that we don't render here, the OS can use its
346 own translation rules instead, so we don't really need to offer
347 everything. To minimize memory consumption we cover three
348 possible situations based on our primary format as detected from
349 selection-coding-system (see setup_config()):
351 - Post CF_TEXT only. Let the OS convert to CF_OEMTEXT and the OS
352 (on NT) or the application (on 9x/Me) convert to
353 CF_UNICODETEXT.
355 - Post CF_OEMTEXT only. Similar automatic conversions happen as
356 for CF_TEXT.
358 - Post CF_UNICODETEXT + CF_TEXT. 9x itself ignores
359 CF_UNICODETEXT, even though some applications can still handle
362 Note 1: We render the less capable CF_TEXT *before* the more
363 capable CF_UNICODETEXT, to prevent clobbering through automatic
364 conversions, just in case.
366 Note 2: We could check os_subtype here and only render the
367 additional CF_TEXT on 9x/Me. But OTOH with
368 current_clipboard_type == CF_UNICODETEXT we don't involve the
369 automatic conversions anywhere else, so to get consistent
370 results, we probably don't want to rely on it here either. */
372 render_locale ();
374 if (current_clipboard_type == CF_UNICODETEXT)
375 render (make_number (CF_TEXT));
376 render (make_number (current_clipboard_type));
378 CloseClipboard ();
380 return Qnil;
383 static void
384 run_protected (Lisp_Object (*code) (Lisp_Object), Lisp_Object arg)
386 /* FIXME: This works but it doesn't feel right. Too much fiddling
387 with global variables and calling strange looking functions. Is
388 this really the right way to run Lisp callbacks? */
390 int owfi;
392 block_input ();
394 /* Fsignal calls emacs_abort () if it sees that waiting_for_input is
395 set. */
396 owfi = waiting_for_input;
397 waiting_for_input = 0;
399 internal_condition_case_1 (code, arg, Qt, lisp_error_handler);
401 waiting_for_input = owfi;
403 unblock_input ();
406 static Lisp_Object
407 lisp_error_handler (Lisp_Object error)
409 Vsignaling_function = Qnil;
410 cmd_error_internal (error, "Error in delayed clipboard rendering: ");
411 Vinhibit_quit = Qt;
412 return Qt;
416 static LRESULT CALLBACK ALIGN_STACK
417 owner_callback (HWND win, UINT msg, WPARAM wp, LPARAM lp)
419 switch (msg)
421 case WM_RENDERFORMAT:
422 ONTRACE (fprintf (stderr, "WM_RENDERFORMAT\n"));
423 run_protected (render, make_number (wp));
424 return 0;
426 case WM_RENDERALLFORMATS:
427 ONTRACE (fprintf (stderr, "WM_RENDERALLFORMATS\n"));
428 run_protected (render_all, Qnil);
429 return 0;
431 case WM_DESTROYCLIPBOARD:
432 if (!modifying_clipboard)
434 ONTRACE (fprintf (stderr, "WM_DESTROYCLIPBOARD (other)\n"));
435 current_text = Qnil;
436 current_coding_system = Qnil;
438 else
440 ONTRACE (fprintf (stderr, "WM_DESTROYCLIPBOARD (self)\n"));
442 return 0;
444 case WM_DESTROY:
445 if (win == clipboard_owner)
446 clipboard_owner = NULL;
447 break;
450 return DefWindowProc (win, msg, wp, lp);
453 static HWND
454 create_owner (void)
456 static const char CLASSNAME[] = "Emacs Clipboard";
457 WNDCLASS wc;
459 memset (&wc, 0, sizeof (wc));
460 wc.lpszClassName = CLASSNAME;
461 wc.lpfnWndProc = owner_callback;
462 RegisterClass (&wc);
464 return CreateWindow (CLASSNAME, CLASSNAME, 0, 0, 0, 0, 0, NULL, NULL,
465 NULL, NULL);
468 /* Called on exit by term_ntproc() in w32.c */
470 void
471 term_w32select (void)
473 /* This is needed to trigger WM_RENDERALLFORMATS. */
474 if (clipboard_owner != NULL)
476 DestroyWindow (clipboard_owner);
477 clipboard_owner = NULL;
481 static void
482 setup_config (void)
484 const char *coding_name;
485 const char *cp;
486 char *end;
487 int slen;
488 Lisp_Object coding_system;
489 Lisp_Object dos_coding_system;
491 CHECK_SYMBOL (Vselection_coding_system);
493 coding_system = NILP (Vnext_selection_coding_system) ?
494 Vselection_coding_system : Vnext_selection_coding_system;
496 dos_coding_system = validate_coding_system (coding_system);
497 if (NILP (dos_coding_system))
498 Fsignal (Qerror,
499 list2 (build_string ("Coding system is invalid or doesn't have "
500 "an eol variant for dos line ends"),
501 coding_system));
503 /* Check if we have it cached */
504 if (!NILP (cfg_coding_system)
505 && EQ (cfg_coding_system, dos_coding_system))
506 return;
507 cfg_coding_system = dos_coding_system;
509 /* Set some sensible fallbacks */
510 cfg_codepage = ANSICP;
511 cfg_lcid = LOCALE_NEUTRAL;
512 cfg_clipboard_type = CF_TEXT;
514 /* Interpret the coding system symbol name */
515 coding_name = SSDATA (SYMBOL_NAME (cfg_coding_system));
517 /* "(.*-)?utf-16.*" -> CF_UNICODETEXT */
518 cp = strstr (coding_name, "utf-16");
519 if (cp != NULL && (cp == coding_name || cp[-1] == '-'))
521 cfg_clipboard_type = CF_UNICODETEXT;
522 return;
525 /* "cp[0-9]+.*" or "windows-[0-9]+.*" -> CF_TEXT or CF_OEMTEXT */
526 slen = strlen (coding_name);
527 if (slen >= 4 && coding_name[0] == 'c' && coding_name[1] == 'p')
528 cp = coding_name + 2;
529 else if (slen >= 10 && memcmp (coding_name, "windows-", 8) == 0)
530 cp = coding_name + 8;
531 else
532 return;
534 end = (char*)cp;
535 cfg_codepage = strtol (cp, &end, 10);
537 /* Error return from strtol() or number of digits < 2 -> Restore the
538 default and drop it. */
539 if (cfg_codepage == 0 || (end-cp) < 2 )
541 cfg_codepage = ANSICP;
542 return;
545 /* Is it the currently active system default? */
546 if (cfg_codepage == ANSICP)
548 /* cfg_clipboard_type = CF_TEXT; */
549 return;
551 if (cfg_codepage == OEMCP)
553 cfg_clipboard_type = CF_OEMTEXT;
554 return;
557 /* Else determine a suitable locale the hard way. */
558 EnumSystemLocales (enum_locale_callback, LCID_INSTALLED);
561 static BOOL WINAPI
562 enum_locale_callback (/*const*/ char* loc_string)
564 LCID lcid;
565 UINT codepage;
567 lcid = strtoul (loc_string, NULL, 16);
569 /* Is the wanted codepage the "ANSI" codepage for this locale? */
570 codepage = cp_from_locale (lcid, CF_TEXT);
571 if (codepage == cfg_codepage)
573 cfg_lcid = lcid;
574 cfg_clipboard_type = CF_TEXT;
575 return FALSE; /* Stop enumeration */
578 /* Is the wanted codepage the OEM codepage for this locale? */
579 codepage = cp_from_locale (lcid, CF_OEMTEXT);
580 if (codepage == cfg_codepage)
582 cfg_lcid = lcid;
583 cfg_clipboard_type = CF_OEMTEXT;
584 return FALSE; /* Stop enumeration */
587 return TRUE; /* Continue enumeration */
590 static UINT
591 cp_from_locale (LCID lcid, UINT format)
593 char buffer[20] = "";
594 UINT variant, cp;
596 variant =
597 format == CF_TEXT ? LOCALE_IDEFAULTANSICODEPAGE : LOCALE_IDEFAULTCODEPAGE;
599 GetLocaleInfo (lcid, variant, buffer, sizeof (buffer));
600 cp = strtoul (buffer, NULL, 10);
602 if (cp == CP_ACP)
603 return ANSICP;
604 else if (cp == CP_OEMCP)
605 return OEMCP;
606 else
607 return cp;
610 static Lisp_Object
611 coding_from_cp (UINT codepage)
613 char buffer[30];
614 sprintf (buffer, "cp%d-dos", (int) codepage);
615 return intern (buffer);
616 /* We don't need to check that this coding system actually exists
617 right here, because that is done later for all coding systems
618 used, regardless of where they originate. */
621 static Lisp_Object
622 validate_coding_system (Lisp_Object coding_system)
624 Lisp_Object eol_type;
626 /* Make sure the input is valid. */
627 if (NILP (Fcoding_system_p (coding_system)))
628 return Qnil;
630 /* Make sure we use a DOS coding system as mandated by the system
631 specs. */
632 eol_type = Fcoding_system_eol_type (coding_system);
634 /* Already a DOS coding system? */
635 if (EQ (eol_type, make_number (1)))
636 return coding_system;
638 /* Get EOL_TYPE vector of the base of CODING_SYSTEM. */
639 if (!VECTORP (eol_type))
641 eol_type = Fcoding_system_eol_type (Fcoding_system_base (coding_system));
642 if (!VECTORP (eol_type))
643 return Qnil;
646 return AREF (eol_type, 1);
649 static void
650 setup_windows_coding_system (Lisp_Object coding_system,
651 struct coding_system * coding)
653 memset (coding, 0, sizeof (*coding));
654 setup_coding_system (coding_system, coding);
656 /* Unset CODING_ANNOTATE_COMPOSITION_MASK. Previous code had
657 comments about crashes in encode_coding_iso2022 trying to
658 dereference a null pointer when composition was on. Selection
659 data should not contain any composition sequence on Windows.
661 CODING_ANNOTATION_MASK also includes
662 CODING_ANNOTATE_DIRECTION_MASK and CODING_ANNOTATE_CHARSET_MASK,
663 which both apply to ISO6429 only. We don't know if these really
664 need to be unset on Windows, but it probably doesn't hurt
665 either. */
666 coding->common_flags &= ~CODING_ANNOTATION_MASK;
667 coding->mode |= CODING_MODE_LAST_BLOCK | CODING_MODE_SAFE_ENCODING;
672 DEFUN ("w32-set-clipboard-data", Fw32_set_clipboard_data,
673 Sw32_set_clipboard_data, 1, 2, 0,
674 doc: /* This sets the clipboard data to the given text. */)
675 (Lisp_Object string, Lisp_Object ignored)
677 BOOL ok = TRUE;
678 int nbytes;
679 unsigned char *src;
680 unsigned char *dst;
681 unsigned char *end;
683 /* This parameter used to be the current frame, but we don't use
684 that any more. */
685 (void) ignored;
687 CHECK_STRING (string);
689 setup_config ();
691 current_text = string;
692 current_coding_system = cfg_coding_system;
693 current_clipboard_type = cfg_clipboard_type;
694 current_lcid = cfg_lcid;
695 current_num_nls = 0;
696 current_requires_encoding = 0;
698 block_input ();
700 /* Check for non-ASCII characters. While we are at it, count the
701 number of LFs, so we know how many CRs we will have to add later
702 (just in the case where we can use our internal ASCII rendering,
703 see code and comment in convert_to_handle_as_ascii() above). */
704 nbytes = SBYTES (string);
705 src = SDATA (string);
707 for (dst = src, end = src+nbytes; dst < end; dst++)
709 if (*dst == '\n')
710 current_num_nls++;
711 else if (*dst >= 0x80 || *dst == 0)
713 current_requires_encoding = 1;
714 break;
718 if (!current_requires_encoding)
720 /* If all we have is ASCII we don't need to pretend we offer
721 anything fancy. */
722 current_coding_system = Qraw_text;
723 current_clipboard_type = CF_TEXT;
724 current_lcid = LOCALE_NEUTRAL;
727 if (!OpenClipboard (clipboard_owner))
728 goto error;
730 ++modifying_clipboard;
731 ok = EmptyClipboard ();
732 --modifying_clipboard;
734 /* If we have something non-ASCII we may want to set a locale. We
735 do that directly (non-delayed), as it's just a small bit. */
736 if (ok)
737 ok = !NILP (render_locale ());
739 if (ok)
741 if (clipboard_owner == NULL)
743 /* If for some reason we don't have a clipboard_owner, we
744 just set the text format as chosen by the configuration
745 and than forget about the whole thing. */
746 ok = !NILP (render (make_number (current_clipboard_type)));
747 current_text = Qnil;
748 current_coding_system = Qnil;
750 else
752 /* Advertise all supported formats so that whatever the
753 requestor chooses, only one encoding step needs to be
754 made. This is intentionally different from what we do in
755 the handler for WM_RENDERALLFORMATS. */
756 SetClipboardData (CF_UNICODETEXT, NULL);
757 SetClipboardData (CF_TEXT, NULL);
758 SetClipboardData (CF_OEMTEXT, NULL);
762 CloseClipboard ();
764 /* With delayed rendering we haven't really "used" this coding
765 system yet, and it's even unclear if we ever will. But this is a
766 way to tell the upper level what we *would* use under ideal
767 circumstances.
769 We don't signal the actually used coding-system later when we
770 finally render, because that can happen at any time and we don't
771 want to disturb the "foreground" action. */
772 if (ok)
773 Vlast_coding_system_used = current_coding_system;
775 Vnext_selection_coding_system = Qnil;
777 if (ok) goto done;
779 error:
781 ok = FALSE;
782 current_text = Qnil;
783 current_coding_system = Qnil;
785 done:
786 unblock_input ();
788 return (ok ? string : Qnil);
792 DEFUN ("w32-get-clipboard-data", Fw32_get_clipboard_data,
793 Sw32_get_clipboard_data, 0, 1, 0,
794 doc: /* This gets the clipboard data in text format. */)
795 (Lisp_Object ignored)
797 HGLOBAL htext;
798 Lisp_Object ret = Qnil;
799 UINT actual_clipboard_type;
800 int use_configured_coding_system = 1;
802 /* This parameter used to be the current frame, but we don't use
803 that any more. */
804 (void) ignored;
806 /* Don't pass our own text from the clipboard (which might be
807 troublesome if the killed text includes null characters). */
808 if (!NILP (current_text))
809 return ret;
811 setup_config ();
812 actual_clipboard_type = cfg_clipboard_type;
814 block_input ();
816 if (!OpenClipboard (clipboard_owner))
817 goto done;
819 if ((htext = GetClipboardData (actual_clipboard_type)) == NULL)
821 /* If we want CF_UNICODETEXT but can't get it, the current
822 coding system is useless. OTOH we can still try and decode
823 CF_TEXT based on the locale that the system gives us and that
824 we get down below. */
825 if (actual_clipboard_type == CF_UNICODETEXT)
827 htext = GetClipboardData (CF_TEXT);
828 if (htext != NULL)
830 actual_clipboard_type = CF_TEXT;
831 use_configured_coding_system = 0;
835 if (htext == NULL)
836 goto closeclip;
839 unsigned char *src;
840 unsigned char *dst;
841 int nbytes;
842 int truelen;
843 int require_decoding = 0;
845 if ((src = (unsigned char *) GlobalLock (htext)) == NULL)
846 goto closeclip;
848 /* If the clipboard data contains any non-ascii code, we need to
849 decode it with a coding system. */
850 if (actual_clipboard_type == CF_UNICODETEXT)
852 nbytes = lstrlenW ((WCHAR *)src) * 2;
853 require_decoding = 1;
855 else
857 int i;
859 nbytes = strlen ((char *)src);
861 for (i = 0; i < nbytes; i++)
863 if (src[i] >= 0x80)
865 require_decoding = 1;
866 break;
871 if (require_decoding)
873 struct coding_system coding;
874 Lisp_Object coding_system = Qnil;
875 Lisp_Object dos_coding_system;
877 /* `next-selection-coding-system' should override everything,
878 even when the locale passed by the system disagrees. The
879 only exception is when `next-selection-coding-system'
880 requested CF_UNICODETEXT and we couldn't get that. */
881 if (use_configured_coding_system
882 && !NILP (Vnext_selection_coding_system))
883 coding_system = Vnext_selection_coding_system;
885 /* If we have CF_TEXT or CF_OEMTEXT, we want to check out
886 CF_LOCALE, too. */
887 else if (actual_clipboard_type != CF_UNICODETEXT)
889 HGLOBAL hlocale;
890 LCID lcid = DEFAULT_LCID;
891 UINT cp;
893 /* Documentation says that the OS always generates
894 CF_LOCALE info automatically, so the locale handle
895 should always be present. Fact is that this is not
896 always true on 9x ;-(. */
897 hlocale = GetClipboardData (CF_LOCALE);
898 if (hlocale != NULL)
900 const LCID * lcid_ptr;
901 lcid_ptr = (const LCID *) GlobalLock (hlocale);
902 if (lcid_ptr != NULL)
904 lcid = *lcid_ptr;
905 GlobalUnlock (hlocale);
908 /* 9x has garbage as the sort order (to be exact there
909 is another instance of the language id in the upper
910 word). We don't care about sort order anyway, so
911 we just filter out the unneeded mis-information to
912 avoid irritations. */
913 lcid = MAKELCID (LANGIDFROMLCID (lcid), SORT_DEFAULT);
916 /* If we are using fallback from CF_UNICODETEXT, we can't
917 use the configured coding system. Also we don't want
918 to use it, if the system has supplied us with a locale
919 and it is not just the system default. */
920 if (!use_configured_coding_system || lcid != DEFAULT_LCID)
922 cp = cp_from_locale (lcid, actual_clipboard_type);
923 /* If it's just our current standard setting anyway,
924 use the coding system that the user has selected.
925 Otherwise create a new spec to match the locale
926 that was specified by the other side or the
927 system. */
928 if (!use_configured_coding_system || cp != cfg_codepage)
929 coding_system = coding_from_cp (cp);
933 if (NILP (coding_system))
934 coding_system = Vselection_coding_system;
935 Vnext_selection_coding_system = Qnil;
937 dos_coding_system = validate_coding_system (coding_system);
938 if (!NILP (dos_coding_system))
940 setup_windows_coding_system (dos_coding_system, &coding);
941 coding.source = src;
942 decode_coding_object (&coding, Qnil, 0, 0, nbytes, nbytes, Qt);
943 ret = coding.dst_object;
945 Vlast_coding_system_used = CODING_ID_NAME (coding.id);
948 else
950 /* FIXME: We may want to repeat the code in this branch for
951 the Unicode case. */
953 /* Need to know final size after CR chars are removed because
954 we can't change the string size manually, and doing an
955 extra copy is silly. We only remove CR when it appears as
956 part of CRLF. */
958 truelen = nbytes;
959 dst = src;
960 /* avoid using strchr because it recomputes the length everytime */
961 while ((dst = memchr (dst, '\r', nbytes - (dst - src))) != NULL)
963 if (dst[1] == '\n') /* safe because of trailing '\0' */
964 truelen--;
965 dst++;
968 ret = make_uninit_string (truelen);
970 /* Convert CRLF line endings (the standard CF_TEXT clipboard
971 format) to LF endings as used internally by Emacs. */
973 dst = SDATA (ret);
974 while (1)
976 unsigned char *next;
977 /* copy next line or remaining bytes excluding '\0' */
978 next = _memccpy (dst, src, '\r', nbytes);
979 if (next)
981 /* copied one line ending with '\r' */
982 int copied = next - dst;
983 nbytes -= copied;
984 dst += copied;
985 src += copied;
986 if (*src == '\n')
987 dst--; /* overwrite '\r' with '\n' */
989 else
990 /* copied remaining partial line -> now finished */
991 break;
994 Vlast_coding_system_used = Qraw_text;
997 GlobalUnlock (htext);
1000 closeclip:
1001 CloseClipboard ();
1003 done:
1004 unblock_input ();
1006 return (ret);
1009 /* Support checking for a clipboard selection. */
1011 DEFUN ("w32-selection-exists-p", Fw32_selection_exists_p, Sw32_selection_exists_p,
1012 0, 2, 0,
1013 doc: /* Whether there is an owner for the given X selection.
1014 SELECTION should be the name of the selection in question, typically
1015 one of the symbols `PRIMARY', `SECONDARY', or `CLIPBOARD'. (X expects
1016 these literal upper-case names.) The symbol nil is the same as
1017 `PRIMARY', and t is the same as `SECONDARY'.
1019 TERMINAL should be a terminal object or a frame specifying the X
1020 server to query. If omitted or nil, that stands for the selected
1021 frame's display, or the first available X display. */)
1022 (Lisp_Object selection, Lisp_Object terminal)
1024 CHECK_SYMBOL (selection);
1026 /* Return nil for PRIMARY and SECONDARY selections; for CLIPBOARD, check
1027 if the clipboard currently has valid text format contents. */
1029 if (EQ (selection, QCLIPBOARD))
1031 Lisp_Object val = Qnil;
1033 setup_config ();
1035 if (OpenClipboard (NULL))
1037 UINT format = 0;
1038 while ((format = EnumClipboardFormats (format)))
1039 /* Check CF_TEXT in addition to cfg_clipboard_type,
1040 because we can fall back on that if CF_UNICODETEXT is
1041 not available. Actually a check for CF_TEXT only
1042 should be enough. */
1043 if (format == cfg_clipboard_type || format == CF_TEXT)
1045 val = Qt;
1046 break;
1048 CloseClipboard ();
1050 return val;
1052 return Qnil;
1055 /* One-time init. Called in the un-dumped Emacs, but not in the
1056 dumped version. */
1058 void
1059 syms_of_w32select (void)
1061 defsubr (&Sw32_set_clipboard_data);
1062 defsubr (&Sw32_get_clipboard_data);
1063 defsubr (&Sw32_selection_exists_p);
1065 DEFVAR_LISP ("selection-coding-system", Vselection_coding_system,
1066 doc: /* Coding system for communicating with other programs.
1068 For MS-Windows and MS-DOS:
1069 When sending or receiving text via selection and clipboard, the text
1070 is encoded or decoded by this coding system. The default value is
1071 the current system default encoding on 9x/Me, `utf-16le-dos'
1072 \(Unicode) on NT/W2K/XP, and `iso-latin-1-dos' on MS-DOS.
1074 For X Windows:
1075 When sending text via selection and clipboard, if the target
1076 data-type matches with the type of this coding system, it is used
1077 for encoding the text. Otherwise (including the case that this
1078 variable is nil), a proper coding system is used as below:
1080 data-type coding system
1081 --------- -------------
1082 UTF8_STRING utf-8
1083 COMPOUND_TEXT compound-text-with-extensions
1084 STRING iso-latin-1
1085 C_STRING no-conversion
1087 When receiving text, if this coding system is non-nil, it is used
1088 for decoding regardless of the data-type. If this is nil, a
1089 proper coding system is used according to the data-type as above.
1091 See also the documentation of the variable `x-select-request-type' how
1092 to control which data-type to request for receiving text.
1094 The default value is nil. */);
1095 /* The actual value is set dynamically in the dumped Emacs, see
1096 below. */
1097 Vselection_coding_system = Qnil;
1099 DEFVAR_LISP ("next-selection-coding-system", Vnext_selection_coding_system,
1100 doc: /* Coding system for the next communication with other programs.
1101 Usually, `selection-coding-system' is used for communicating with
1102 other programs (X Windows clients or MS Windows programs). But, if this
1103 variable is set, it is used for the next communication only.
1104 After the communication, this variable is set to nil. */);
1105 Vnext_selection_coding_system = Qnil;
1107 DEFSYM (QCLIPBOARD, "CLIPBOARD");
1109 cfg_coding_system = Qnil; staticpro (&cfg_coding_system);
1110 current_text = Qnil; staticpro (&current_text);
1111 current_coding_system = Qnil; staticpro (&current_coding_system);
1113 DEFSYM (Qutf_16le_dos, "utf-16le-dos");
1114 QANSICP = Qnil; staticpro (&QANSICP);
1115 QOEMCP = Qnil; staticpro (&QOEMCP);
1118 /* One-time init. Called in the dumped Emacs, but not in the
1119 un-dumped version. */
1121 void
1122 globals_of_w32select (void)
1124 DEFAULT_LCID = GetUserDefaultLCID ();
1125 /* Drop the sort order from the LCID, so we can compare this with
1126 CF_LOCALE objects that have the same fix on 9x. */
1127 DEFAULT_LCID = MAKELCID (LANGIDFROMLCID (DEFAULT_LCID), SORT_DEFAULT);
1129 ANSICP = GetACP ();
1130 OEMCP = GetOEMCP ();
1132 QANSICP = coding_from_cp (ANSICP);
1133 QOEMCP = coding_from_cp (OEMCP);
1135 if (os_subtype == OS_NT)
1136 Vselection_coding_system = Qutf_16le_dos;
1137 else if (inhibit_window_system)
1138 Vselection_coding_system = QOEMCP;
1139 else
1140 Vselection_coding_system = QANSICP;
1142 clipboard_owner = create_owner ();