comparison src/clipboard.c @ 19774:00a1b89256ea v8.2.0443

patch 8.2.0443: clipboard code is spread out Commit: https://github.com/vim/vim/commit/45fffdf10b7cb6e59794e76e9b8a2930fcb4b192 Author: Bram Moolenaar <Bram@vim.org> Date: Tue Mar 24 21:42:01 2020 +0100 patch 8.2.0443: clipboard code is spread out Problem: Clipboard code is spread out. Solution: Move clipboard code to its own file. (Yegappan Lakshmanan, closes #5827)
author Bram Moolenaar <Bram@vim.org>
date Tue, 24 Mar 2020 21:45:04 +0100
parents
children aadd1cae2ff5
comparison
equal deleted inserted replaced
19773:c8242fe426a7 19774:00a1b89256ea
1 /* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10 /*
11 * clipboard.c: Functions to handle the clipboard
12 */
13
14 #include "vim.h"
15
16 #ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
17 # define WIN32_LEAN_AND_MEAN
18 # include <windows.h>
19 # include "winclip.pro"
20 #endif
21
22 // Functions for copying and pasting text between applications.
23 // This is always included in a GUI version, but may also be included when the
24 // clipboard and mouse is available to a terminal version such as xterm.
25 // Note: there are some more functions in ops.c that handle selection stuff.
26 //
27 // Also note that the majority of functions here deal with the X 'primary'
28 // (visible - for Visual mode use) selection, and only that. There are no
29 // versions of these for the 'clipboard' selection, as Visual mode has no use
30 // for them.
31
32 #if defined(FEAT_CLIPBOARD) || defined(PROTO)
33
34 /*
35 * Selection stuff using Visual mode, for cutting and pasting text to other
36 * windows.
37 */
38
39 /*
40 * Call this to initialise the clipboard. Pass it FALSE if the clipboard code
41 * is included, but the clipboard can not be used, or TRUE if the clipboard can
42 * be used. Eg unix may call this with FALSE, then call it again with TRUE if
43 * the GUI starts.
44 */
45 void
46 clip_init(int can_use)
47 {
48 Clipboard_T *cb;
49
50 cb = &clip_star;
51 for (;;)
52 {
53 cb->available = can_use;
54 cb->owned = FALSE;
55 cb->start.lnum = 0;
56 cb->start.col = 0;
57 cb->end.lnum = 0;
58 cb->end.col = 0;
59 cb->state = SELECT_CLEARED;
60
61 if (cb == &clip_plus)
62 break;
63 cb = &clip_plus;
64 }
65 }
66
67 /*
68 * Check whether the VIsual area has changed, and if so try to become the owner
69 * of the selection, and free any old converted selection we may still have
70 * lying around. If the VIsual mode has ended, make a copy of what was
71 * selected so we can still give it to others. Will probably have to make sure
72 * this is called whenever VIsual mode is ended.
73 */
74 void
75 clip_update_selection(Clipboard_T *clip)
76 {
77 pos_T start, end;
78
79 // If visual mode is only due to a redo command ("."), then ignore it
80 if (!redo_VIsual_busy && VIsual_active && (State & NORMAL))
81 {
82 if (LT_POS(VIsual, curwin->w_cursor))
83 {
84 start = VIsual;
85 end = curwin->w_cursor;
86 if (has_mbyte)
87 end.col += (*mb_ptr2len)(ml_get_cursor()) - 1;
88 }
89 else
90 {
91 start = curwin->w_cursor;
92 end = VIsual;
93 }
94 if (!EQUAL_POS(clip->start, start)
95 || !EQUAL_POS(clip->end, end)
96 || clip->vmode != VIsual_mode)
97 {
98 clip_clear_selection(clip);
99 clip->start = start;
100 clip->end = end;
101 clip->vmode = VIsual_mode;
102 clip_free_selection(clip);
103 clip_own_selection(clip);
104 clip_gen_set_selection(clip);
105 }
106 }
107 }
108
109 static int
110 clip_gen_own_selection(Clipboard_T *cbd)
111 {
112 #ifdef FEAT_XCLIPBOARD
113 # ifdef FEAT_GUI
114 if (gui.in_use)
115 return clip_mch_own_selection(cbd);
116 else
117 # endif
118 return clip_xterm_own_selection(cbd);
119 #else
120 return clip_mch_own_selection(cbd);
121 #endif
122 }
123
124 void
125 clip_own_selection(Clipboard_T *cbd)
126 {
127 /*
128 * Also want to check somehow that we are reading from the keyboard rather
129 * than a mapping etc.
130 */
131 #ifdef FEAT_X11
132 // Always own the selection, we might have lost it without being
133 // notified, e.g. during a ":sh" command.
134 if (cbd->available)
135 {
136 int was_owned = cbd->owned;
137
138 cbd->owned = (clip_gen_own_selection(cbd) == OK);
139 if (!was_owned && (cbd == &clip_star || cbd == &clip_plus))
140 {
141 // May have to show a different kind of highlighting for the
142 // selected area. There is no specific redraw command for this,
143 // just redraw all windows on the current buffer.
144 if (cbd->owned
145 && (get_real_state() == VISUAL
146 || get_real_state() == SELECTMODE)
147 && (cbd == &clip_star ? clip_isautosel_star()
148 : clip_isautosel_plus())
149 && HL_ATTR(HLF_V) != HL_ATTR(HLF_VNC))
150 redraw_curbuf_later(INVERTED_ALL);
151 }
152 }
153 #else
154 // Only own the clipboard when we didn't own it yet.
155 if (!cbd->owned && cbd->available)
156 cbd->owned = (clip_gen_own_selection(cbd) == OK);
157 #endif
158 }
159
160 static void
161 clip_gen_lose_selection(Clipboard_T *cbd)
162 {
163 #ifdef FEAT_XCLIPBOARD
164 # ifdef FEAT_GUI
165 if (gui.in_use)
166 clip_mch_lose_selection(cbd);
167 else
168 # endif
169 clip_xterm_lose_selection(cbd);
170 #else
171 clip_mch_lose_selection(cbd);
172 #endif
173 }
174
175 void
176 clip_lose_selection(Clipboard_T *cbd)
177 {
178 #ifdef FEAT_X11
179 int was_owned = cbd->owned;
180 #endif
181 int visual_selection = FALSE;
182
183 if (cbd == &clip_star || cbd == &clip_plus)
184 visual_selection = TRUE;
185
186 clip_free_selection(cbd);
187 cbd->owned = FALSE;
188 if (visual_selection)
189 clip_clear_selection(cbd);
190 clip_gen_lose_selection(cbd);
191 #ifdef FEAT_X11
192 if (visual_selection)
193 {
194 // May have to show a different kind of highlighting for the selected
195 // area. There is no specific redraw command for this, just redraw all
196 // windows on the current buffer.
197 if (was_owned
198 && (get_real_state() == VISUAL
199 || get_real_state() == SELECTMODE)
200 && (cbd == &clip_star ?
201 clip_isautosel_star() : clip_isautosel_plus())
202 && HL_ATTR(HLF_V) != HL_ATTR(HLF_VNC))
203 {
204 update_curbuf(INVERTED_ALL);
205 setcursor();
206 cursor_on();
207 out_flush_cursor(TRUE, FALSE);
208 }
209 }
210 #endif
211 }
212
213 static void
214 clip_copy_selection(Clipboard_T *clip)
215 {
216 if (VIsual_active && (State & NORMAL) && clip->available)
217 {
218 clip_update_selection(clip);
219 clip_free_selection(clip);
220 clip_own_selection(clip);
221 if (clip->owned)
222 clip_get_selection(clip);
223 clip_gen_set_selection(clip);
224 }
225 }
226
227 /*
228 * Save and restore clip_unnamed before doing possibly many changes. This
229 * prevents accessing the clipboard very often which might slow down Vim
230 * considerably.
231 */
232 static int global_change_count = 0; // if set, inside a start_global_changes
233 static int clipboard_needs_update = FALSE; // clipboard needs to be updated
234 static int clip_did_set_selection = TRUE;
235
236 /*
237 * Save clip_unnamed and reset it.
238 */
239 void
240 start_global_changes(void)
241 {
242 if (++global_change_count > 1)
243 return;
244 clip_unnamed_saved = clip_unnamed;
245 clipboard_needs_update = FALSE;
246
247 if (clip_did_set_selection)
248 {
249 clip_unnamed = 0;
250 clip_did_set_selection = FALSE;
251 }
252 }
253
254 /*
255 * Return TRUE if setting the clipboard was postponed, it already contains the
256 * right text.
257 */
258 static int
259 is_clipboard_needs_update()
260 {
261 return clipboard_needs_update;
262 }
263
264 /*
265 * Restore clip_unnamed and set the selection when needed.
266 */
267 void
268 end_global_changes(void)
269 {
270 if (--global_change_count > 0)
271 // recursive
272 return;
273 if (!clip_did_set_selection)
274 {
275 clip_did_set_selection = TRUE;
276 clip_unnamed = clip_unnamed_saved;
277 clip_unnamed_saved = 0;
278 if (clipboard_needs_update)
279 {
280 // only store something in the clipboard,
281 // if we have yanked anything to it
282 if (clip_unnamed & CLIP_UNNAMED)
283 {
284 clip_own_selection(&clip_star);
285 clip_gen_set_selection(&clip_star);
286 }
287 if (clip_unnamed & CLIP_UNNAMED_PLUS)
288 {
289 clip_own_selection(&clip_plus);
290 clip_gen_set_selection(&clip_plus);
291 }
292 }
293 }
294 clipboard_needs_update = FALSE;
295 }
296
297 /*
298 * Called when Visual mode is ended: update the selection.
299 */
300 void
301 clip_auto_select(void)
302 {
303 if (clip_isautosel_star())
304 clip_copy_selection(&clip_star);
305 if (clip_isautosel_plus())
306 clip_copy_selection(&clip_plus);
307 }
308
309 /*
310 * Return TRUE if automatic selection of Visual area is desired for the *
311 * register.
312 */
313 int
314 clip_isautosel_star(void)
315 {
316 return (
317 #ifdef FEAT_GUI
318 gui.in_use ? (vim_strchr(p_go, GO_ASEL) != NULL) :
319 #endif
320 clip_autoselect_star);
321 }
322
323 /*
324 * Return TRUE if automatic selection of Visual area is desired for the +
325 * register.
326 */
327 int
328 clip_isautosel_plus(void)
329 {
330 return (
331 #ifdef FEAT_GUI
332 gui.in_use ? (vim_strchr(p_go, GO_ASELPLUS) != NULL) :
333 #endif
334 clip_autoselect_plus);
335 }
336
337
338 /*
339 * Stuff for general mouse selection, without using Visual mode.
340 */
341
342 /*
343 * Compare two screen positions ala strcmp()
344 */
345 static int
346 clip_compare_pos(
347 int row1,
348 int col1,
349 int row2,
350 int col2)
351 {
352 if (row1 > row2) return(1);
353 if (row1 < row2) return(-1);
354 if (col1 > col2) return(1);
355 if (col1 < col2) return(-1);
356 return(0);
357 }
358
359 // "how" flags for clip_invert_area()
360 #define CLIP_CLEAR 1
361 #define CLIP_SET 2
362 #define CLIP_TOGGLE 3
363
364 /*
365 * Invert or un-invert a rectangle of the screen.
366 * "invert" is true if the result is inverted.
367 */
368 static void
369 clip_invert_rectangle(
370 Clipboard_T *cbd UNUSED,
371 int row_arg,
372 int col_arg,
373 int height_arg,
374 int width_arg,
375 int invert)
376 {
377 int row = row_arg;
378 int col = col_arg;
379 int height = height_arg;
380 int width = width_arg;
381
382 #ifdef FEAT_PROP_POPUP
383 // this goes on top of all popup windows
384 screen_zindex = CLIP_ZINDEX;
385
386 if (col < cbd->min_col)
387 {
388 width -= cbd->min_col - col;
389 col = cbd->min_col;
390 }
391 if (width > cbd->max_col - col)
392 width = cbd->max_col - col;
393 if (row < cbd->min_row)
394 {
395 height -= cbd->min_row - row;
396 row = cbd->min_row;
397 }
398 if (height > cbd->max_row - row + 1)
399 height = cbd->max_row - row + 1;
400 #endif
401 #ifdef FEAT_GUI
402 if (gui.in_use)
403 gui_mch_invert_rectangle(row, col, height, width);
404 else
405 #endif
406 screen_draw_rectangle(row, col, height, width, invert);
407 #ifdef FEAT_PROP_POPUP
408 screen_zindex = 0;
409 #endif
410 }
411
412 /*
413 * Invert a region of the display between a starting and ending row and column
414 * Values for "how":
415 * CLIP_CLEAR: undo inversion
416 * CLIP_SET: set inversion
417 * CLIP_TOGGLE: set inversion if pos1 < pos2, undo inversion otherwise.
418 * 0: invert (GUI only).
419 */
420 static void
421 clip_invert_area(
422 Clipboard_T *cbd,
423 int row1,
424 int col1,
425 int row2,
426 int col2,
427 int how)
428 {
429 int invert = FALSE;
430 int max_col;
431
432 #ifdef FEAT_PROP_POPUP
433 max_col = cbd->max_col - 1;
434 #else
435 max_col = Columns - 1;
436 #endif
437
438 if (how == CLIP_SET)
439 invert = TRUE;
440
441 // Swap the from and to positions so the from is always before
442 if (clip_compare_pos(row1, col1, row2, col2) > 0)
443 {
444 int tmp_row, tmp_col;
445
446 tmp_row = row1;
447 tmp_col = col1;
448 row1 = row2;
449 col1 = col2;
450 row2 = tmp_row;
451 col2 = tmp_col;
452 }
453 else if (how == CLIP_TOGGLE)
454 invert = TRUE;
455
456 // If all on the same line, do it the easy way
457 if (row1 == row2)
458 {
459 clip_invert_rectangle(cbd, row1, col1, 1, col2 - col1, invert);
460 }
461 else
462 {
463 // Handle a piece of the first line
464 if (col1 > 0)
465 {
466 clip_invert_rectangle(cbd, row1, col1, 1,
467 (int)Columns - col1, invert);
468 row1++;
469 }
470
471 // Handle a piece of the last line
472 if (col2 < max_col)
473 {
474 clip_invert_rectangle(cbd, row2, 0, 1, col2, invert);
475 row2--;
476 }
477
478 // Handle the rectangle that's left
479 if (row2 >= row1)
480 clip_invert_rectangle(cbd, row1, 0, row2 - row1 + 1,
481 (int)Columns, invert);
482 }
483 }
484
485 /*
486 * Start, continue or end a modeless selection. Used when editing the
487 * command-line, in the cmdline window and when the mouse is in a popup window.
488 */
489 void
490 clip_modeless(int button, int is_click, int is_drag)
491 {
492 int repeat;
493
494 repeat = ((clip_star.mode == SELECT_MODE_CHAR
495 || clip_star.mode == SELECT_MODE_LINE)
496 && (mod_mask & MOD_MASK_2CLICK))
497 || (clip_star.mode == SELECT_MODE_WORD
498 && (mod_mask & MOD_MASK_3CLICK));
499 if (is_click && button == MOUSE_RIGHT)
500 {
501 // Right mouse button: If there was no selection, start one.
502 // Otherwise extend the existing selection.
503 if (clip_star.state == SELECT_CLEARED)
504 clip_start_selection(mouse_col, mouse_row, FALSE);
505 clip_process_selection(button, mouse_col, mouse_row, repeat);
506 }
507 else if (is_click)
508 clip_start_selection(mouse_col, mouse_row, repeat);
509 else if (is_drag)
510 {
511 // Don't try extending a selection if there isn't one. Happens when
512 // button-down is in the cmdline and them moving mouse upwards.
513 if (clip_star.state != SELECT_CLEARED)
514 clip_process_selection(button, mouse_col, mouse_row, repeat);
515 }
516 else // release
517 clip_process_selection(MOUSE_RELEASE, mouse_col, mouse_row, FALSE);
518 }
519
520 /*
521 * Update the currently selected region by adding and/or subtracting from the
522 * beginning or end and inverting the changed area(s).
523 */
524 static void
525 clip_update_modeless_selection(
526 Clipboard_T *cb,
527 int row1,
528 int col1,
529 int row2,
530 int col2)
531 {
532 // See if we changed at the beginning of the selection
533 if (row1 != cb->start.lnum || col1 != (int)cb->start.col)
534 {
535 clip_invert_area(cb, row1, col1, (int)cb->start.lnum, cb->start.col,
536 CLIP_TOGGLE);
537 cb->start.lnum = row1;
538 cb->start.col = col1;
539 }
540
541 // See if we changed at the end of the selection
542 if (row2 != cb->end.lnum || col2 != (int)cb->end.col)
543 {
544 clip_invert_area(cb, (int)cb->end.lnum, cb->end.col, row2, col2,
545 CLIP_TOGGLE);
546 cb->end.lnum = row2;
547 cb->end.col = col2;
548 }
549 }
550
551 /*
552 * Find the starting and ending positions of the word at the given row and
553 * column. Only white-separated words are recognized here.
554 */
555 #define CHAR_CLASS(c) (c <= ' ' ? ' ' : vim_iswordc(c))
556
557 static void
558 clip_get_word_boundaries(Clipboard_T *cb, int row, int col)
559 {
560 int start_class;
561 int temp_col;
562 char_u *p;
563 int mboff;
564
565 if (row >= screen_Rows || col >= screen_Columns || ScreenLines == NULL)
566 return;
567
568 p = ScreenLines + LineOffset[row];
569 // Correct for starting in the right halve of a double-wide char
570 if (enc_dbcs != 0)
571 col -= dbcs_screen_head_off(p, p + col);
572 else if (enc_utf8 && p[col] == 0)
573 --col;
574 start_class = CHAR_CLASS(p[col]);
575
576 temp_col = col;
577 for ( ; temp_col > 0; temp_col--)
578 if (enc_dbcs != 0
579 && (mboff = dbcs_screen_head_off(p, p + temp_col - 1)) > 0)
580 temp_col -= mboff;
581 else if (CHAR_CLASS(p[temp_col - 1]) != start_class
582 && !(enc_utf8 && p[temp_col - 1] == 0))
583 break;
584 cb->word_start_col = temp_col;
585
586 temp_col = col;
587 for ( ; temp_col < screen_Columns; temp_col++)
588 if (enc_dbcs != 0 && dbcs_ptr2cells(p + temp_col) == 2)
589 ++temp_col;
590 else if (CHAR_CLASS(p[temp_col]) != start_class
591 && !(enc_utf8 && p[temp_col] == 0))
592 break;
593 cb->word_end_col = temp_col;
594 }
595
596 /*
597 * Find the column position for the last non-whitespace character on the given
598 * line at or before start_col.
599 */
600 static int
601 clip_get_line_end(Clipboard_T *cbd UNUSED, int row)
602 {
603 int i;
604
605 if (row >= screen_Rows || ScreenLines == NULL)
606 return 0;
607 for (i =
608 #ifdef FEAT_PROP_POPUP
609 cbd->max_col;
610 #else
611 screen_Columns;
612 #endif
613 i > 0; i--)
614 if (ScreenLines[LineOffset[row] + i - 1] != ' ')
615 break;
616 return i;
617 }
618
619 /*
620 * Start the selection
621 */
622 void
623 clip_start_selection(int col, int row, int repeated_click)
624 {
625 Clipboard_T *cb = &clip_star;
626 #ifdef FEAT_PROP_POPUP
627 win_T *wp;
628 int row_cp = row;
629 int col_cp = col;
630
631 wp = mouse_find_win(&row_cp, &col_cp, FIND_POPUP);
632 if (wp != NULL && WIN_IS_POPUP(wp)
633 && popup_is_in_scrollbar(wp, row_cp, col_cp))
634 // click or double click in scrollbar does not start a selection
635 return;
636 #endif
637
638 if (cb->state == SELECT_DONE)
639 clip_clear_selection(cb);
640
641 row = check_row(row);
642 col = check_col(col);
643 col = mb_fix_col(col, row);
644
645 cb->start.lnum = row;
646 cb->start.col = col;
647 cb->end = cb->start;
648 cb->origin_row = (short_u)cb->start.lnum;
649 cb->state = SELECT_IN_PROGRESS;
650 #ifdef FEAT_PROP_POPUP
651 if (wp != NULL && WIN_IS_POPUP(wp))
652 {
653 // Click in a popup window restricts selection to that window,
654 // excluding the border.
655 cb->min_col = wp->w_wincol + wp->w_popup_border[3];
656 cb->max_col = wp->w_wincol + popup_width(wp)
657 - wp->w_popup_border[1] - wp->w_has_scrollbar;
658 if (cb->max_col > screen_Columns)
659 cb->max_col = screen_Columns;
660 cb->min_row = wp->w_winrow + wp->w_popup_border[0];
661 cb->max_row = wp->w_winrow + popup_height(wp) - 1
662 - wp->w_popup_border[2];
663 }
664 else
665 {
666 cb->min_col = 0;
667 cb->max_col = screen_Columns;
668 cb->min_row = 0;
669 cb->max_row = screen_Rows;
670 }
671 #endif
672
673 if (repeated_click)
674 {
675 if (++cb->mode > SELECT_MODE_LINE)
676 cb->mode = SELECT_MODE_CHAR;
677 }
678 else
679 cb->mode = SELECT_MODE_CHAR;
680
681 #ifdef FEAT_GUI
682 // clear the cursor until the selection is made
683 if (gui.in_use)
684 gui_undraw_cursor();
685 #endif
686
687 switch (cb->mode)
688 {
689 case SELECT_MODE_CHAR:
690 cb->origin_start_col = cb->start.col;
691 cb->word_end_col = clip_get_line_end(cb, (int)cb->start.lnum);
692 break;
693
694 case SELECT_MODE_WORD:
695 clip_get_word_boundaries(cb, (int)cb->start.lnum, cb->start.col);
696 cb->origin_start_col = cb->word_start_col;
697 cb->origin_end_col = cb->word_end_col;
698
699 clip_invert_area(cb, (int)cb->start.lnum, cb->word_start_col,
700 (int)cb->end.lnum, cb->word_end_col, CLIP_SET);
701 cb->start.col = cb->word_start_col;
702 cb->end.col = cb->word_end_col;
703 break;
704
705 case SELECT_MODE_LINE:
706 clip_invert_area(cb, (int)cb->start.lnum, 0, (int)cb->start.lnum,
707 (int)Columns, CLIP_SET);
708 cb->start.col = 0;
709 cb->end.col = Columns;
710 break;
711 }
712
713 cb->prev = cb->start;
714
715 #ifdef DEBUG_SELECTION
716 printf("Selection started at (%ld,%d)\n", cb->start.lnum, cb->start.col);
717 #endif
718 }
719
720 /*
721 * Continue processing the selection
722 */
723 void
724 clip_process_selection(
725 int button,
726 int col,
727 int row,
728 int_u repeated_click)
729 {
730 Clipboard_T *cb = &clip_star;
731 int diff;
732 int slen = 1; // cursor shape width
733
734 if (button == MOUSE_RELEASE)
735 {
736 if (cb->state != SELECT_IN_PROGRESS)
737 return;
738
739 // Check to make sure we have something selected
740 if (cb->start.lnum == cb->end.lnum && cb->start.col == cb->end.col)
741 {
742 #ifdef FEAT_GUI
743 if (gui.in_use)
744 gui_update_cursor(FALSE, FALSE);
745 #endif
746 cb->state = SELECT_CLEARED;
747 return;
748 }
749
750 #ifdef DEBUG_SELECTION
751 printf("Selection ended: (%ld,%d) to (%ld,%d)\n", cb->start.lnum,
752 cb->start.col, cb->end.lnum, cb->end.col);
753 #endif
754 if (clip_isautosel_star()
755 || (
756 #ifdef FEAT_GUI
757 gui.in_use ? (vim_strchr(p_go, GO_ASELML) != NULL) :
758 #endif
759 clip_autoselectml))
760 clip_copy_modeless_selection(FALSE);
761 #ifdef FEAT_GUI
762 if (gui.in_use)
763 gui_update_cursor(FALSE, FALSE);
764 #endif
765
766 cb->state = SELECT_DONE;
767 return;
768 }
769
770 row = check_row(row);
771 col = check_col(col);
772 col = mb_fix_col(col, row);
773
774 if (col == (int)cb->prev.col && row == cb->prev.lnum && !repeated_click)
775 return;
776
777 /*
778 * When extending the selection with the right mouse button, swap the
779 * start and end if the position is before half the selection
780 */
781 if (cb->state == SELECT_DONE && button == MOUSE_RIGHT)
782 {
783 /*
784 * If the click is before the start, or the click is inside the
785 * selection and the start is the closest side, set the origin to the
786 * end of the selection.
787 */
788 if (clip_compare_pos(row, col, (int)cb->start.lnum, cb->start.col) < 0
789 || (clip_compare_pos(row, col,
790 (int)cb->end.lnum, cb->end.col) < 0
791 && (((cb->start.lnum == cb->end.lnum
792 && cb->end.col - col > col - cb->start.col))
793 || ((diff = (cb->end.lnum - row) -
794 (row - cb->start.lnum)) > 0
795 || (diff == 0 && col < (int)(cb->start.col +
796 cb->end.col) / 2)))))
797 {
798 cb->origin_row = (short_u)cb->end.lnum;
799 cb->origin_start_col = cb->end.col - 1;
800 cb->origin_end_col = cb->end.col;
801 }
802 else
803 {
804 cb->origin_row = (short_u)cb->start.lnum;
805 cb->origin_start_col = cb->start.col;
806 cb->origin_end_col = cb->start.col;
807 }
808 if (cb->mode == SELECT_MODE_WORD && !repeated_click)
809 cb->mode = SELECT_MODE_CHAR;
810 }
811
812 // set state, for when using the right mouse button
813 cb->state = SELECT_IN_PROGRESS;
814
815 #ifdef DEBUG_SELECTION
816 printf("Selection extending to (%d,%d)\n", row, col);
817 #endif
818
819 if (repeated_click && ++cb->mode > SELECT_MODE_LINE)
820 cb->mode = SELECT_MODE_CHAR;
821
822 switch (cb->mode)
823 {
824 case SELECT_MODE_CHAR:
825 // If we're on a different line, find where the line ends
826 if (row != cb->prev.lnum)
827 cb->word_end_col = clip_get_line_end(cb, row);
828
829 // See if we are before or after the origin of the selection
830 if (clip_compare_pos(row, col, cb->origin_row,
831 cb->origin_start_col) >= 0)
832 {
833 if (col >= (int)cb->word_end_col)
834 clip_update_modeless_selection(cb, cb->origin_row,
835 cb->origin_start_col, row, (int)Columns);
836 else
837 {
838 if (has_mbyte && mb_lefthalve(row, col))
839 slen = 2;
840 clip_update_modeless_selection(cb, cb->origin_row,
841 cb->origin_start_col, row, col + slen);
842 }
843 }
844 else
845 {
846 if (has_mbyte
847 && mb_lefthalve(cb->origin_row, cb->origin_start_col))
848 slen = 2;
849 if (col >= (int)cb->word_end_col)
850 clip_update_modeless_selection(cb, row, cb->word_end_col,
851 cb->origin_row, cb->origin_start_col + slen);
852 else
853 clip_update_modeless_selection(cb, row, col,
854 cb->origin_row, cb->origin_start_col + slen);
855 }
856 break;
857
858 case SELECT_MODE_WORD:
859 // If we are still within the same word, do nothing
860 if (row == cb->prev.lnum && col >= (int)cb->word_start_col
861 && col < (int)cb->word_end_col && !repeated_click)
862 return;
863
864 // Get new word boundaries
865 clip_get_word_boundaries(cb, row, col);
866
867 // Handle being after the origin point of selection
868 if (clip_compare_pos(row, col, cb->origin_row,
869 cb->origin_start_col) >= 0)
870 clip_update_modeless_selection(cb, cb->origin_row,
871 cb->origin_start_col, row, cb->word_end_col);
872 else
873 clip_update_modeless_selection(cb, row, cb->word_start_col,
874 cb->origin_row, cb->origin_end_col);
875 break;
876
877 case SELECT_MODE_LINE:
878 if (row == cb->prev.lnum && !repeated_click)
879 return;
880
881 if (clip_compare_pos(row, col, cb->origin_row,
882 cb->origin_start_col) >= 0)
883 clip_update_modeless_selection(cb, cb->origin_row, 0, row,
884 (int)Columns);
885 else
886 clip_update_modeless_selection(cb, row, 0, cb->origin_row,
887 (int)Columns);
888 break;
889 }
890
891 cb->prev.lnum = row;
892 cb->prev.col = col;
893
894 #ifdef DEBUG_SELECTION
895 printf("Selection is: (%ld,%d) to (%ld,%d)\n", cb->start.lnum,
896 cb->start.col, cb->end.lnum, cb->end.col);
897 #endif
898 }
899
900 # if defined(FEAT_GUI) || defined(PROTO)
901 /*
902 * Redraw part of the selection if character at "row,col" is inside of it.
903 * Only used for the GUI.
904 */
905 void
906 clip_may_redraw_selection(int row, int col, int len)
907 {
908 int start = col;
909 int end = col + len;
910
911 if (clip_star.state != SELECT_CLEARED
912 && row >= clip_star.start.lnum
913 && row <= clip_star.end.lnum)
914 {
915 if (row == clip_star.start.lnum && start < (int)clip_star.start.col)
916 start = clip_star.start.col;
917 if (row == clip_star.end.lnum && end > (int)clip_star.end.col)
918 end = clip_star.end.col;
919 if (end > start)
920 clip_invert_area(&clip_star, row, start, row, end, 0);
921 }
922 }
923 # endif
924
925 /*
926 * Called from outside to clear selected region from the display
927 */
928 void
929 clip_clear_selection(Clipboard_T *cbd)
930 {
931
932 if (cbd->state == SELECT_CLEARED)
933 return;
934
935 clip_invert_area(cbd, (int)cbd->start.lnum, cbd->start.col,
936 (int)cbd->end.lnum, cbd->end.col, CLIP_CLEAR);
937 cbd->state = SELECT_CLEARED;
938 }
939
940 /*
941 * Clear the selection if any lines from "row1" to "row2" are inside of it.
942 */
943 void
944 clip_may_clear_selection(int row1, int row2)
945 {
946 if (clip_star.state == SELECT_DONE
947 && row2 >= clip_star.start.lnum
948 && row1 <= clip_star.end.lnum)
949 clip_clear_selection(&clip_star);
950 }
951
952 /*
953 * Called before the screen is scrolled up or down. Adjusts the line numbers
954 * of the selection. Call with big number when clearing the screen.
955 */
956 void
957 clip_scroll_selection(
958 int rows) // negative for scroll down
959 {
960 int lnum;
961
962 if (clip_star.state == SELECT_CLEARED)
963 return;
964
965 lnum = clip_star.start.lnum - rows;
966 if (lnum <= 0)
967 clip_star.start.lnum = 0;
968 else if (lnum >= screen_Rows) // scrolled off of the screen
969 clip_star.state = SELECT_CLEARED;
970 else
971 clip_star.start.lnum = lnum;
972
973 lnum = clip_star.end.lnum - rows;
974 if (lnum < 0) // scrolled off of the screen
975 clip_star.state = SELECT_CLEARED;
976 else if (lnum >= screen_Rows)
977 clip_star.end.lnum = screen_Rows - 1;
978 else
979 clip_star.end.lnum = lnum;
980 }
981
982 /*
983 * Copy the currently selected area into the '*' register so it will be
984 * available for pasting.
985 * When "both" is TRUE also copy to the '+' register.
986 */
987 void
988 clip_copy_modeless_selection(int both UNUSED)
989 {
990 char_u *buffer;
991 char_u *bufp;
992 int row;
993 int start_col;
994 int end_col;
995 int line_end_col;
996 int add_newline_flag = FALSE;
997 int len;
998 char_u *p;
999 int row1 = clip_star.start.lnum;
1000 int col1 = clip_star.start.col;
1001 int row2 = clip_star.end.lnum;
1002 int col2 = clip_star.end.col;
1003
1004 // Can't use ScreenLines unless initialized
1005 if (ScreenLines == NULL)
1006 return;
1007
1008 /*
1009 * Make sure row1 <= row2, and if row1 == row2 that col1 <= col2.
1010 */
1011 if (row1 > row2)
1012 {
1013 row = row1; row1 = row2; row2 = row;
1014 row = col1; col1 = col2; col2 = row;
1015 }
1016 else if (row1 == row2 && col1 > col2)
1017 {
1018 row = col1; col1 = col2; col2 = row;
1019 }
1020 #ifdef FEAT_PROP_POPUP
1021 if (col1 < clip_star.min_col)
1022 col1 = clip_star.min_col;
1023 if (col2 > clip_star.max_col)
1024 col2 = clip_star.max_col;
1025 if (row1 > clip_star.max_row || row2 < clip_star.min_row)
1026 return;
1027 if (row1 < clip_star.min_row)
1028 row1 = clip_star.min_row;
1029 if (row2 > clip_star.max_row)
1030 row2 = clip_star.max_row;
1031 #endif
1032 // correct starting point for being on right halve of double-wide char
1033 p = ScreenLines + LineOffset[row1];
1034 if (enc_dbcs != 0)
1035 col1 -= (*mb_head_off)(p, p + col1);
1036 else if (enc_utf8 && p[col1] == 0)
1037 --col1;
1038
1039 // Create a temporary buffer for storing the text
1040 len = (row2 - row1 + 1) * Columns + 1;
1041 if (enc_dbcs != 0)
1042 len *= 2; // max. 2 bytes per display cell
1043 else if (enc_utf8)
1044 len *= MB_MAXBYTES;
1045 buffer = alloc(len);
1046 if (buffer == NULL) // out of memory
1047 return;
1048
1049 // Process each row in the selection
1050 for (bufp = buffer, row = row1; row <= row2; row++)
1051 {
1052 if (row == row1)
1053 start_col = col1;
1054 else
1055 #ifdef FEAT_PROP_POPUP
1056 start_col = clip_star.min_col;
1057 #else
1058 start_col = 0;
1059 #endif
1060
1061 if (row == row2)
1062 end_col = col2;
1063 else
1064 #ifdef FEAT_PROP_POPUP
1065 end_col = clip_star.max_col;
1066 #else
1067 end_col = Columns;
1068 #endif
1069
1070 line_end_col = clip_get_line_end(&clip_star, row);
1071
1072 // See if we need to nuke some trailing whitespace
1073 if (end_col >=
1074 #ifdef FEAT_PROP_POPUP
1075 clip_star.max_col
1076 #else
1077 Columns
1078 #endif
1079 && (row < row2 || end_col > line_end_col))
1080 {
1081 // Get rid of trailing whitespace
1082 end_col = line_end_col;
1083 if (end_col < start_col)
1084 end_col = start_col;
1085
1086 // If the last line extended to the end, add an extra newline
1087 if (row == row2)
1088 add_newline_flag = TRUE;
1089 }
1090
1091 // If after the first row, we need to always add a newline
1092 if (row > row1 && !LineWraps[row - 1])
1093 *bufp++ = NL;
1094
1095 // Safetey check for in case resizing went wrong
1096 if (row < screen_Rows && end_col <= screen_Columns)
1097 {
1098 if (enc_dbcs != 0)
1099 {
1100 int i;
1101
1102 p = ScreenLines + LineOffset[row];
1103 for (i = start_col; i < end_col; ++i)
1104 if (enc_dbcs == DBCS_JPNU && p[i] == 0x8e)
1105 {
1106 // single-width double-byte char
1107 *bufp++ = 0x8e;
1108 *bufp++ = ScreenLines2[LineOffset[row] + i];
1109 }
1110 else
1111 {
1112 *bufp++ = p[i];
1113 if (MB_BYTE2LEN(p[i]) == 2)
1114 *bufp++ = p[++i];
1115 }
1116 }
1117 else if (enc_utf8)
1118 {
1119 int off;
1120 int i;
1121 int ci;
1122
1123 off = LineOffset[row];
1124 for (i = start_col; i < end_col; ++i)
1125 {
1126 // The base character is either in ScreenLinesUC[] or
1127 // ScreenLines[].
1128 if (ScreenLinesUC[off + i] == 0)
1129 *bufp++ = ScreenLines[off + i];
1130 else
1131 {
1132 bufp += utf_char2bytes(ScreenLinesUC[off + i], bufp);
1133 for (ci = 0; ci < Screen_mco; ++ci)
1134 {
1135 // Add a composing character.
1136 if (ScreenLinesC[ci][off + i] == 0)
1137 break;
1138 bufp += utf_char2bytes(ScreenLinesC[ci][off + i],
1139 bufp);
1140 }
1141 }
1142 // Skip right halve of double-wide character.
1143 if (ScreenLines[off + i + 1] == 0)
1144 ++i;
1145 }
1146 }
1147 else
1148 {
1149 STRNCPY(bufp, ScreenLines + LineOffset[row] + start_col,
1150 end_col - start_col);
1151 bufp += end_col - start_col;
1152 }
1153 }
1154 }
1155
1156 // Add a newline at the end if the selection ended there
1157 if (add_newline_flag)
1158 *bufp++ = NL;
1159
1160 // First cleanup any old selection and become the owner.
1161 clip_free_selection(&clip_star);
1162 clip_own_selection(&clip_star);
1163
1164 // Yank the text into the '*' register.
1165 clip_yank_selection(MCHAR, buffer, (long)(bufp - buffer), &clip_star);
1166
1167 // Make the register contents available to the outside world.
1168 clip_gen_set_selection(&clip_star);
1169
1170 #ifdef FEAT_X11
1171 if (both)
1172 {
1173 // Do the same for the '+' register.
1174 clip_free_selection(&clip_plus);
1175 clip_own_selection(&clip_plus);
1176 clip_yank_selection(MCHAR, buffer, (long)(bufp - buffer), &clip_plus);
1177 clip_gen_set_selection(&clip_plus);
1178 }
1179 #endif
1180 vim_free(buffer);
1181 }
1182
1183 void
1184 clip_gen_set_selection(Clipboard_T *cbd)
1185 {
1186 if (!clip_did_set_selection)
1187 {
1188 // Updating postponed, so that accessing the system clipboard won't
1189 // hang Vim when accessing it many times (e.g. on a :g command).
1190 if ((cbd == &clip_plus && (clip_unnamed_saved & CLIP_UNNAMED_PLUS))
1191 || (cbd == &clip_star && (clip_unnamed_saved & CLIP_UNNAMED)))
1192 {
1193 clipboard_needs_update = TRUE;
1194 return;
1195 }
1196 }
1197 #ifdef FEAT_XCLIPBOARD
1198 # ifdef FEAT_GUI
1199 if (gui.in_use)
1200 clip_mch_set_selection(cbd);
1201 else
1202 # endif
1203 clip_xterm_set_selection(cbd);
1204 #else
1205 clip_mch_set_selection(cbd);
1206 #endif
1207 }
1208
1209 static void
1210 clip_gen_request_selection(Clipboard_T *cbd)
1211 {
1212 #ifdef FEAT_XCLIPBOARD
1213 # ifdef FEAT_GUI
1214 if (gui.in_use)
1215 clip_mch_request_selection(cbd);
1216 else
1217 # endif
1218 clip_xterm_request_selection(cbd);
1219 #else
1220 clip_mch_request_selection(cbd);
1221 #endif
1222 }
1223
1224 #if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD) && defined(USE_SYSTEM)) \
1225 || defined(PROTO)
1226 static int
1227 clip_x11_owner_exists(Clipboard_T *cbd)
1228 {
1229 return XGetSelectionOwner(X_DISPLAY, cbd->sel_atom) != None;
1230 }
1231 #endif
1232
1233 #if (defined(FEAT_X11) && defined(USE_SYSTEM)) || defined(PROTO)
1234 int
1235 clip_gen_owner_exists(Clipboard_T *cbd UNUSED)
1236 {
1237 #ifdef FEAT_XCLIPBOARD
1238 # ifdef FEAT_GUI_GTK
1239 if (gui.in_use)
1240 return clip_gtk_owner_exists(cbd);
1241 else
1242 # endif
1243 return clip_x11_owner_exists(cbd);
1244 #else
1245 return TRUE;
1246 #endif
1247 }
1248 #endif
1249
1250 /*
1251 * Extract the items in the 'clipboard' option and set global values.
1252 * Return an error message or NULL for success.
1253 */
1254 char *
1255 check_clipboard_option(void)
1256 {
1257 int new_unnamed = 0;
1258 int new_autoselect_star = FALSE;
1259 int new_autoselect_plus = FALSE;
1260 int new_autoselectml = FALSE;
1261 int new_html = FALSE;
1262 regprog_T *new_exclude_prog = NULL;
1263 char *errmsg = NULL;
1264 char_u *p;
1265
1266 for (p = p_cb; *p != NUL; )
1267 {
1268 if (STRNCMP(p, "unnamed", 7) == 0 && (p[7] == ',' || p[7] == NUL))
1269 {
1270 new_unnamed |= CLIP_UNNAMED;
1271 p += 7;
1272 }
1273 else if (STRNCMP(p, "unnamedplus", 11) == 0
1274 && (p[11] == ',' || p[11] == NUL))
1275 {
1276 new_unnamed |= CLIP_UNNAMED_PLUS;
1277 p += 11;
1278 }
1279 else if (STRNCMP(p, "autoselect", 10) == 0
1280 && (p[10] == ',' || p[10] == NUL))
1281 {
1282 new_autoselect_star = TRUE;
1283 p += 10;
1284 }
1285 else if (STRNCMP(p, "autoselectplus", 14) == 0
1286 && (p[14] == ',' || p[14] == NUL))
1287 {
1288 new_autoselect_plus = TRUE;
1289 p += 14;
1290 }
1291 else if (STRNCMP(p, "autoselectml", 12) == 0
1292 && (p[12] == ',' || p[12] == NUL))
1293 {
1294 new_autoselectml = TRUE;
1295 p += 12;
1296 }
1297 else if (STRNCMP(p, "html", 4) == 0 && (p[4] == ',' || p[4] == NUL))
1298 {
1299 new_html = TRUE;
1300 p += 4;
1301 }
1302 else if (STRNCMP(p, "exclude:", 8) == 0 && new_exclude_prog == NULL)
1303 {
1304 p += 8;
1305 new_exclude_prog = vim_regcomp(p, RE_MAGIC);
1306 if (new_exclude_prog == NULL)
1307 errmsg = e_invarg;
1308 break;
1309 }
1310 else
1311 {
1312 errmsg = e_invarg;
1313 break;
1314 }
1315 if (*p == ',')
1316 ++p;
1317 }
1318 if (errmsg == NULL)
1319 {
1320 clip_unnamed = new_unnamed;
1321 clip_autoselect_star = new_autoselect_star;
1322 clip_autoselect_plus = new_autoselect_plus;
1323 clip_autoselectml = new_autoselectml;
1324 clip_html = new_html;
1325 vim_regfree(clip_exclude_prog);
1326 clip_exclude_prog = new_exclude_prog;
1327 #ifdef FEAT_GUI_GTK
1328 if (gui.in_use)
1329 {
1330 gui_gtk_set_selection_targets();
1331 gui_gtk_set_dnd_targets();
1332 }
1333 #endif
1334 }
1335 else
1336 vim_regfree(new_exclude_prog);
1337
1338 return errmsg;
1339 }
1340
1341 /*
1342 * Stuff for the X clipboard. Shared between VMS and Unix.
1343 */
1344
1345 #if defined(FEAT_XCLIPBOARD) || defined(FEAT_GUI_X11) || defined(PROTO)
1346 # include <X11/Xatom.h>
1347 # include <X11/Intrinsic.h>
1348
1349 /*
1350 * Open the application context (if it hasn't been opened yet).
1351 * Used for Motif and Athena GUI and the xterm clipboard.
1352 */
1353 void
1354 open_app_context(void)
1355 {
1356 if (app_context == NULL)
1357 {
1358 XtToolkitInitialize();
1359 app_context = XtCreateApplicationContext();
1360 }
1361 }
1362
1363 static Atom vim_atom; // Vim's own special selection format
1364 static Atom vimenc_atom; // Vim's extended selection format
1365 static Atom utf8_atom;
1366 static Atom compound_text_atom;
1367 static Atom text_atom;
1368 static Atom targets_atom;
1369 static Atom timestamp_atom; // Used to get a timestamp
1370
1371 void
1372 x11_setup_atoms(Display *dpy)
1373 {
1374 vim_atom = XInternAtom(dpy, VIM_ATOM_NAME, False);
1375 vimenc_atom = XInternAtom(dpy, VIMENC_ATOM_NAME,False);
1376 utf8_atom = XInternAtom(dpy, "UTF8_STRING", False);
1377 compound_text_atom = XInternAtom(dpy, "COMPOUND_TEXT", False);
1378 text_atom = XInternAtom(dpy, "TEXT", False);
1379 targets_atom = XInternAtom(dpy, "TARGETS", False);
1380 clip_star.sel_atom = XA_PRIMARY;
1381 clip_plus.sel_atom = XInternAtom(dpy, "CLIPBOARD", False);
1382 timestamp_atom = XInternAtom(dpy, "TIMESTAMP", False);
1383 }
1384
1385 /*
1386 * X Selection stuff, for cutting and pasting text to other windows.
1387 */
1388
1389 static Boolean
1390 clip_x11_convert_selection_cb(
1391 Widget w UNUSED,
1392 Atom *sel_atom,
1393 Atom *target,
1394 Atom *type,
1395 XtPointer *value,
1396 long_u *length,
1397 int *format)
1398 {
1399 static char_u *save_result = NULL;
1400 static long_u save_length = 0;
1401 char_u *string;
1402 int motion_type;
1403 Clipboard_T *cbd;
1404 int i;
1405
1406 if (*sel_atom == clip_plus.sel_atom)
1407 cbd = &clip_plus;
1408 else
1409 cbd = &clip_star;
1410
1411 if (!cbd->owned)
1412 return False; // Shouldn't ever happen
1413
1414 // requestor wants to know what target types we support
1415 if (*target == targets_atom)
1416 {
1417 static Atom array[7];
1418
1419 *value = (XtPointer)array;
1420 i = 0;
1421 array[i++] = targets_atom;
1422 array[i++] = vimenc_atom;
1423 array[i++] = vim_atom;
1424 if (enc_utf8)
1425 array[i++] = utf8_atom;
1426 array[i++] = XA_STRING;
1427 array[i++] = text_atom;
1428 array[i++] = compound_text_atom;
1429
1430 *type = XA_ATOM;
1431 // This used to be: *format = sizeof(Atom) * 8; but that caused
1432 // crashes on 64 bit machines. (Peter Derr)
1433 *format = 32;
1434 *length = i;
1435 return True;
1436 }
1437
1438 if ( *target != XA_STRING
1439 && *target != vimenc_atom
1440 && (*target != utf8_atom || !enc_utf8)
1441 && *target != vim_atom
1442 && *target != text_atom
1443 && *target != compound_text_atom)
1444 return False;
1445
1446 clip_get_selection(cbd);
1447 motion_type = clip_convert_selection(&string, length, cbd);
1448 if (motion_type < 0)
1449 return False;
1450
1451 // For our own format, the first byte contains the motion type
1452 if (*target == vim_atom)
1453 (*length)++;
1454
1455 // Our own format with encoding: motion 'encoding' NUL text
1456 if (*target == vimenc_atom)
1457 *length += STRLEN(p_enc) + 2;
1458
1459 if (save_length < *length || save_length / 2 >= *length)
1460 *value = XtRealloc((char *)save_result, (Cardinal)*length + 1);
1461 else
1462 *value = save_result;
1463 if (*value == NULL)
1464 {
1465 vim_free(string);
1466 return False;
1467 }
1468 save_result = (char_u *)*value;
1469 save_length = *length;
1470
1471 if (*target == XA_STRING || (*target == utf8_atom && enc_utf8))
1472 {
1473 mch_memmove(save_result, string, (size_t)(*length));
1474 *type = *target;
1475 }
1476 else if (*target == compound_text_atom || *target == text_atom)
1477 {
1478 XTextProperty text_prop;
1479 char *string_nt = (char *)save_result;
1480 int conv_result;
1481
1482 // create NUL terminated string which XmbTextListToTextProperty wants
1483 mch_memmove(string_nt, string, (size_t)*length);
1484 string_nt[*length] = NUL;
1485 conv_result = XmbTextListToTextProperty(X_DISPLAY, (char **)&string_nt,
1486 1, XCompoundTextStyle, &text_prop);
1487 if (conv_result != Success)
1488 {
1489 vim_free(string);
1490 return False;
1491 }
1492 *value = (XtPointer)(text_prop.value); // from plain text
1493 *length = text_prop.nitems;
1494 *type = compound_text_atom;
1495 XtFree((char *)save_result);
1496 save_result = (char_u *)*value;
1497 save_length = *length;
1498 }
1499 else if (*target == vimenc_atom)
1500 {
1501 int l = STRLEN(p_enc);
1502
1503 save_result[0] = motion_type;
1504 STRCPY(save_result + 1, p_enc);
1505 mch_memmove(save_result + l + 2, string, (size_t)(*length - l - 2));
1506 *type = vimenc_atom;
1507 }
1508 else
1509 {
1510 save_result[0] = motion_type;
1511 mch_memmove(save_result + 1, string, (size_t)(*length - 1));
1512 *type = vim_atom;
1513 }
1514 *format = 8; // 8 bits per char
1515 vim_free(string);
1516 return True;
1517 }
1518
1519 static void
1520 clip_x11_lose_ownership_cb(Widget w UNUSED, Atom *sel_atom)
1521 {
1522 if (*sel_atom == clip_plus.sel_atom)
1523 clip_lose_selection(&clip_plus);
1524 else
1525 clip_lose_selection(&clip_star);
1526 }
1527
1528 static void
1529 clip_x11_notify_cb(Widget w UNUSED, Atom *sel_atom UNUSED, Atom *target UNUSED)
1530 {
1531 // To prevent automatically freeing the selection value.
1532 }
1533
1534 /*
1535 * Property callback to get a timestamp for XtOwnSelection.
1536 */
1537 static void
1538 clip_x11_timestamp_cb(
1539 Widget w,
1540 XtPointer n UNUSED,
1541 XEvent *event,
1542 Boolean *cont UNUSED)
1543 {
1544 Atom actual_type;
1545 int format;
1546 unsigned long nitems, bytes_after;
1547 unsigned char *prop=NULL;
1548 XPropertyEvent *xproperty=&event->xproperty;
1549
1550 // Must be a property notify, state can't be Delete (True), has to be
1551 // one of the supported selection types.
1552 if (event->type != PropertyNotify || xproperty->state
1553 || (xproperty->atom != clip_star.sel_atom
1554 && xproperty->atom != clip_plus.sel_atom))
1555 return;
1556
1557 if (XGetWindowProperty(xproperty->display, xproperty->window,
1558 xproperty->atom, 0, 0, False, timestamp_atom, &actual_type, &format,
1559 &nitems, &bytes_after, &prop))
1560 return;
1561
1562 if (prop)
1563 XFree(prop);
1564
1565 // Make sure the property type is "TIMESTAMP" and it's 32 bits.
1566 if (actual_type != timestamp_atom || format != 32)
1567 return;
1568
1569 // Get the selection, using the event timestamp.
1570 if (XtOwnSelection(w, xproperty->atom, xproperty->time,
1571 clip_x11_convert_selection_cb, clip_x11_lose_ownership_cb,
1572 clip_x11_notify_cb) == OK)
1573 {
1574 // Set the "owned" flag now, there may have been a call to
1575 // lose_ownership_cb in between.
1576 if (xproperty->atom == clip_plus.sel_atom)
1577 clip_plus.owned = TRUE;
1578 else
1579 clip_star.owned = TRUE;
1580 }
1581 }
1582
1583 void
1584 x11_setup_selection(Widget w)
1585 {
1586 XtAddEventHandler(w, PropertyChangeMask, False,
1587 /*(XtEventHandler)*/clip_x11_timestamp_cb, (XtPointer)NULL);
1588 }
1589
1590 static void
1591 clip_x11_request_selection_cb(
1592 Widget w UNUSED,
1593 XtPointer success,
1594 Atom *sel_atom,
1595 Atom *type,
1596 XtPointer value,
1597 long_u *length,
1598 int *format)
1599 {
1600 int motion_type = MAUTO;
1601 long_u len;
1602 char_u *p;
1603 char **text_list = NULL;
1604 Clipboard_T *cbd;
1605 char_u *tmpbuf = NULL;
1606
1607 if (*sel_atom == clip_plus.sel_atom)
1608 cbd = &clip_plus;
1609 else
1610 cbd = &clip_star;
1611
1612 if (value == NULL || *length == 0)
1613 {
1614 clip_free_selection(cbd); // nothing received, clear register
1615 *(int *)success = FALSE;
1616 return;
1617 }
1618 p = (char_u *)value;
1619 len = *length;
1620 if (*type == vim_atom)
1621 {
1622 motion_type = *p++;
1623 len--;
1624 }
1625
1626 else if (*type == vimenc_atom)
1627 {
1628 char_u *enc;
1629 vimconv_T conv;
1630 int convlen;
1631
1632 motion_type = *p++;
1633 --len;
1634
1635 enc = p;
1636 p += STRLEN(p) + 1;
1637 len -= p - enc;
1638
1639 // If the encoding of the text is different from 'encoding', attempt
1640 // converting it.
1641 conv.vc_type = CONV_NONE;
1642 convert_setup(&conv, enc, p_enc);
1643 if (conv.vc_type != CONV_NONE)
1644 {
1645 convlen = len; // Need to use an int here.
1646 tmpbuf = string_convert(&conv, p, &convlen);
1647 len = convlen;
1648 if (tmpbuf != NULL)
1649 p = tmpbuf;
1650 convert_setup(&conv, NULL, NULL);
1651 }
1652 }
1653
1654 else if (*type == compound_text_atom
1655 || *type == utf8_atom
1656 || (enc_dbcs != 0 && *type == text_atom))
1657 {
1658 XTextProperty text_prop;
1659 int n_text = 0;
1660 int status;
1661
1662 text_prop.value = (unsigned char *)value;
1663 text_prop.encoding = *type;
1664 text_prop.format = *format;
1665 text_prop.nitems = len;
1666 #if defined(X_HAVE_UTF8_STRING)
1667 if (*type == utf8_atom)
1668 status = Xutf8TextPropertyToTextList(X_DISPLAY, &text_prop,
1669 &text_list, &n_text);
1670 else
1671 #endif
1672 status = XmbTextPropertyToTextList(X_DISPLAY, &text_prop,
1673 &text_list, &n_text);
1674 if (status != Success || n_text < 1)
1675 {
1676 *(int *)success = FALSE;
1677 return;
1678 }
1679 p = (char_u *)text_list[0];
1680 len = STRLEN(p);
1681 }
1682 clip_yank_selection(motion_type, p, (long)len, cbd);
1683
1684 if (text_list != NULL)
1685 XFreeStringList(text_list);
1686 vim_free(tmpbuf);
1687 XtFree((char *)value);
1688 *(int *)success = TRUE;
1689 }
1690
1691 void
1692 clip_x11_request_selection(
1693 Widget myShell,
1694 Display *dpy,
1695 Clipboard_T *cbd)
1696 {
1697 XEvent event;
1698 Atom type;
1699 static int success;
1700 int i;
1701 time_t start_time;
1702 int timed_out = FALSE;
1703
1704 for (i = 0; i < 6; i++)
1705 {
1706 switch (i)
1707 {
1708 case 0: type = vimenc_atom; break;
1709 case 1: type = vim_atom; break;
1710 case 2: type = utf8_atom; break;
1711 case 3: type = compound_text_atom; break;
1712 case 4: type = text_atom; break;
1713 default: type = XA_STRING;
1714 }
1715 if (type == utf8_atom
1716 # if defined(X_HAVE_UTF8_STRING)
1717 && !enc_utf8
1718 # endif
1719 )
1720 // Only request utf-8 when 'encoding' is utf8 and
1721 // Xutf8TextPropertyToTextList is available.
1722 continue;
1723 success = MAYBE;
1724 XtGetSelectionValue(myShell, cbd->sel_atom, type,
1725 clip_x11_request_selection_cb, (XtPointer)&success, CurrentTime);
1726
1727 // Make sure the request for the selection goes out before waiting for
1728 // a response.
1729 XFlush(dpy);
1730
1731 /*
1732 * Wait for result of selection request, otherwise if we type more
1733 * characters, then they will appear before the one that requested the
1734 * paste! Don't worry, we will catch up with any other events later.
1735 */
1736 start_time = time(NULL);
1737 while (success == MAYBE)
1738 {
1739 if (XCheckTypedEvent(dpy, PropertyNotify, &event)
1740 || XCheckTypedEvent(dpy, SelectionNotify, &event)
1741 || XCheckTypedEvent(dpy, SelectionRequest, &event))
1742 {
1743 // This is where clip_x11_request_selection_cb() should be
1744 // called. It may actually happen a bit later, so we loop
1745 // until "success" changes.
1746 // We may get a SelectionRequest here and if we don't handle
1747 // it we hang. KDE klipper does this, for example.
1748 // We need to handle a PropertyNotify for large selections.
1749 XtDispatchEvent(&event);
1750 continue;
1751 }
1752
1753 // Time out after 2 to 3 seconds to avoid that we hang when the
1754 // other process doesn't respond. Note that the SelectionNotify
1755 // event may still come later when the selection owner comes back
1756 // to life and the text gets inserted unexpectedly. Don't know
1757 // why that happens or how to avoid that :-(.
1758 if (time(NULL) > start_time + 2)
1759 {
1760 timed_out = TRUE;
1761 break;
1762 }
1763
1764 // Do we need this? Probably not.
1765 XSync(dpy, False);
1766
1767 // Wait for 1 msec to avoid that we eat up all CPU time.
1768 ui_delay(1L, TRUE);
1769 }
1770
1771 if (success == TRUE)
1772 return;
1773
1774 // don't do a retry with another type after timing out, otherwise we
1775 // hang for 15 seconds.
1776 if (timed_out)
1777 break;
1778 }
1779
1780 // Final fallback position - use the X CUT_BUFFER0 store
1781 yank_cut_buffer0(dpy, cbd);
1782 }
1783
1784 void
1785 clip_x11_lose_selection(Widget myShell, Clipboard_T *cbd)
1786 {
1787 XtDisownSelection(myShell, cbd->sel_atom,
1788 XtLastTimestampProcessed(XtDisplay(myShell)));
1789 }
1790
1791 int
1792 clip_x11_own_selection(Widget myShell, Clipboard_T *cbd)
1793 {
1794 // When using the GUI we have proper timestamps, use the one of the last
1795 // event. When in the console we don't get events (the terminal gets
1796 // them), Get the time by a zero-length append, clip_x11_timestamp_cb will
1797 // be called with the current timestamp.
1798 #ifdef FEAT_GUI
1799 if (gui.in_use)
1800 {
1801 if (XtOwnSelection(myShell, cbd->sel_atom,
1802 XtLastTimestampProcessed(XtDisplay(myShell)),
1803 clip_x11_convert_selection_cb, clip_x11_lose_ownership_cb,
1804 clip_x11_notify_cb) == False)
1805 return FAIL;
1806 }
1807 else
1808 #endif
1809 {
1810 if (!XChangeProperty(XtDisplay(myShell), XtWindow(myShell),
1811 cbd->sel_atom, timestamp_atom, 32, PropModeAppend, NULL, 0))
1812 return FAIL;
1813 }
1814 // Flush is required in a terminal as nothing else is doing it.
1815 XFlush(XtDisplay(myShell));
1816 return OK;
1817 }
1818
1819 /*
1820 * Send the current selection to the clipboard. Do nothing for X because we
1821 * will fill in the selection only when requested by another app.
1822 */
1823 void
1824 clip_x11_set_selection(Clipboard_T *cbd UNUSED)
1825 {
1826 }
1827
1828 #endif
1829
1830 #if defined(FEAT_XCLIPBOARD) || defined(FEAT_GUI_X11) \
1831 || defined(FEAT_GUI_GTK) || defined(PROTO)
1832 /*
1833 * Get the contents of the X CUT_BUFFER0 and put it in "cbd".
1834 */
1835 void
1836 yank_cut_buffer0(Display *dpy, Clipboard_T *cbd)
1837 {
1838 int nbytes = 0;
1839 char_u *buffer = (char_u *)XFetchBuffer(dpy, &nbytes, 0);
1840
1841 if (nbytes > 0)
1842 {
1843 int done = FALSE;
1844
1845 // CUT_BUFFER0 is supposed to be always latin1. Convert to 'enc' when
1846 // using a multi-byte encoding. Conversion between two 8-bit
1847 // character sets usually fails and the text might actually be in
1848 // 'enc' anyway.
1849 if (has_mbyte)
1850 {
1851 char_u *conv_buf;
1852 vimconv_T vc;
1853
1854 vc.vc_type = CONV_NONE;
1855 if (convert_setup(&vc, (char_u *)"latin1", p_enc) == OK)
1856 {
1857 conv_buf = string_convert(&vc, buffer, &nbytes);
1858 if (conv_buf != NULL)
1859 {
1860 clip_yank_selection(MCHAR, conv_buf, (long)nbytes, cbd);
1861 vim_free(conv_buf);
1862 done = TRUE;
1863 }
1864 convert_setup(&vc, NULL, NULL);
1865 }
1866 }
1867 if (!done) // use the text without conversion
1868 clip_yank_selection(MCHAR, buffer, (long)nbytes, cbd);
1869 XFree((void *)buffer);
1870 if (p_verbose > 0)
1871 {
1872 verbose_enter();
1873 verb_msg(_("Used CUT_BUFFER0 instead of empty selection"));
1874 verbose_leave();
1875 }
1876 }
1877 }
1878 #endif
1879
1880 /*
1881 * SELECTION / PRIMARY ('*')
1882 *
1883 * Text selection stuff that uses the GUI selection register '*'. When using a
1884 * GUI this may be text from another window, otherwise it is the last text we
1885 * had highlighted with VIsual mode. With mouse support, clicking the middle
1886 * button performs the paste, otherwise you will need to do <"*p>. "
1887 * If not under X, it is synonymous with the clipboard register '+'.
1888 *
1889 * X CLIPBOARD ('+')
1890 *
1891 * Text selection stuff that uses the GUI clipboard register '+'.
1892 * Under X, this matches the standard cut/paste buffer CLIPBOARD selection.
1893 * It will be used for unnamed cut/pasting is 'clipboard' contains "unnamed",
1894 * otherwise you will need to do <"+p>. "
1895 * If not under X, it is synonymous with the selection register '*'.
1896 */
1897
1898 /*
1899 * Routine to export any final X selection we had to the environment
1900 * so that the text is still available after Vim has exited. X selections
1901 * only exist while the owning application exists, so we write to the
1902 * permanent (while X runs) store CUT_BUFFER0.
1903 * Dump the CLIPBOARD selection if we own it (it's logically the more
1904 * 'permanent' of the two), otherwise the PRIMARY one.
1905 * For now, use a hard-coded sanity limit of 1Mb of data.
1906 */
1907 #if (defined(FEAT_X11) && defined(FEAT_CLIPBOARD)) || defined(PROTO)
1908 void
1909 x11_export_final_selection(void)
1910 {
1911 Display *dpy;
1912 char_u *str = NULL;
1913 long_u len = 0;
1914 int motion_type = -1;
1915
1916 # ifdef FEAT_GUI
1917 if (gui.in_use)
1918 dpy = X_DISPLAY;
1919 else
1920 # endif
1921 # ifdef FEAT_XCLIPBOARD
1922 dpy = xterm_dpy;
1923 # else
1924 return;
1925 # endif
1926
1927 // Get selection to export
1928 if (clip_plus.owned)
1929 motion_type = clip_convert_selection(&str, &len, &clip_plus);
1930 else if (clip_star.owned)
1931 motion_type = clip_convert_selection(&str, &len, &clip_star);
1932
1933 // Check it's OK
1934 if (dpy != NULL && str != NULL && motion_type >= 0
1935 && len < 1024*1024 && len > 0)
1936 {
1937 int ok = TRUE;
1938
1939 // The CUT_BUFFER0 is supposed to always contain latin1. Convert from
1940 // 'enc' when it is a multi-byte encoding. When 'enc' is an 8-bit
1941 // encoding conversion usually doesn't work, so keep the text as-is.
1942 if (has_mbyte)
1943 {
1944 vimconv_T vc;
1945
1946 vc.vc_type = CONV_NONE;
1947 if (convert_setup(&vc, p_enc, (char_u *)"latin1") == OK)
1948 {
1949 int intlen = len;
1950 char_u *conv_str;
1951
1952 vc.vc_fail = TRUE;
1953 conv_str = string_convert(&vc, str, &intlen);
1954 len = intlen;
1955 if (conv_str != NULL)
1956 {
1957 vim_free(str);
1958 str = conv_str;
1959 }
1960 else
1961 {
1962 ok = FALSE;
1963 }
1964 convert_setup(&vc, NULL, NULL);
1965 }
1966 else
1967 {
1968 ok = FALSE;
1969 }
1970 }
1971
1972 // Do not store the string if conversion failed. Better to use any
1973 // other selection than garbled text.
1974 if (ok)
1975 {
1976 XStoreBuffer(dpy, (char *)str, (int)len, 0);
1977 XFlush(dpy);
1978 }
1979 }
1980
1981 vim_free(str);
1982 }
1983 #endif
1984
1985 void
1986 clip_free_selection(Clipboard_T *cbd)
1987 {
1988 yankreg_T *y_ptr = get_y_current();
1989
1990 if (cbd == &clip_plus)
1991 set_y_current(get_y_register(PLUS_REGISTER));
1992 else
1993 set_y_current(get_y_register(STAR_REGISTER));
1994 free_yank_all();
1995 get_y_current()->y_size = 0;
1996 set_y_current(y_ptr);
1997 }
1998
1999 /*
2000 * Get the selected text and put it in register '*' or '+'.
2001 */
2002 void
2003 clip_get_selection(Clipboard_T *cbd)
2004 {
2005 yankreg_T *old_y_previous, *old_y_current;
2006 pos_T old_cursor;
2007 pos_T old_visual;
2008 int old_visual_mode;
2009 colnr_T old_curswant;
2010 int old_set_curswant;
2011 pos_T old_op_start, old_op_end;
2012 oparg_T oa;
2013 cmdarg_T ca;
2014
2015 if (cbd->owned)
2016 {
2017 if ((cbd == &clip_plus
2018 && get_y_register(PLUS_REGISTER)->y_array != NULL)
2019 || (cbd == &clip_star
2020 && get_y_register(STAR_REGISTER)->y_array != NULL))
2021 return;
2022
2023 // Get the text between clip_star.start & clip_star.end
2024 old_y_previous = get_y_previous();
2025 old_y_current = get_y_current();
2026 old_cursor = curwin->w_cursor;
2027 old_curswant = curwin->w_curswant;
2028 old_set_curswant = curwin->w_set_curswant;
2029 old_op_start = curbuf->b_op_start;
2030 old_op_end = curbuf->b_op_end;
2031 old_visual = VIsual;
2032 old_visual_mode = VIsual_mode;
2033 clear_oparg(&oa);
2034 oa.regname = (cbd == &clip_plus ? '+' : '*');
2035 oa.op_type = OP_YANK;
2036 vim_memset(&ca, 0, sizeof(ca));
2037 ca.oap = &oa;
2038 ca.cmdchar = 'y';
2039 ca.count1 = 1;
2040 ca.retval = CA_NO_ADJ_OP_END;
2041 do_pending_operator(&ca, 0, TRUE);
2042 set_y_previous(old_y_previous);
2043 set_y_current(old_y_current);
2044 curwin->w_cursor = old_cursor;
2045 changed_cline_bef_curs(); // need to update w_virtcol et al
2046 curwin->w_curswant = old_curswant;
2047 curwin->w_set_curswant = old_set_curswant;
2048 curbuf->b_op_start = old_op_start;
2049 curbuf->b_op_end = old_op_end;
2050 VIsual = old_visual;
2051 VIsual_mode = old_visual_mode;
2052 }
2053 else if (!is_clipboard_needs_update())
2054 {
2055 clip_free_selection(cbd);
2056
2057 // Try to get selected text from another window
2058 clip_gen_request_selection(cbd);
2059 }
2060 }
2061
2062 /*
2063 * Convert from the GUI selection string into the '*'/'+' register.
2064 */
2065 void
2066 clip_yank_selection(
2067 int type,
2068 char_u *str,
2069 long len,
2070 Clipboard_T *cbd)
2071 {
2072 yankreg_T *y_ptr;
2073
2074 if (cbd == &clip_plus)
2075 y_ptr = get_y_register(PLUS_REGISTER);
2076 else
2077 y_ptr = get_y_register(STAR_REGISTER);
2078
2079 clip_free_selection(cbd);
2080
2081 str_to_reg(y_ptr, type, str, len, 0L, FALSE);
2082 }
2083
2084 /*
2085 * Convert the '*'/'+' register into a GUI selection string returned in *str
2086 * with length *len.
2087 * Returns the motion type, or -1 for failure.
2088 */
2089 int
2090 clip_convert_selection(char_u **str, long_u *len, Clipboard_T *cbd)
2091 {
2092 char_u *p;
2093 int lnum;
2094 int i, j;
2095 int_u eolsize;
2096 yankreg_T *y_ptr;
2097
2098 if (cbd == &clip_plus)
2099 y_ptr = get_y_register(PLUS_REGISTER);
2100 else
2101 y_ptr = get_y_register(STAR_REGISTER);
2102
2103 # ifdef USE_CRNL
2104 eolsize = 2;
2105 # else
2106 eolsize = 1;
2107 # endif
2108
2109 *str = NULL;
2110 *len = 0;
2111 if (y_ptr->y_array == NULL)
2112 return -1;
2113
2114 for (i = 0; i < y_ptr->y_size; i++)
2115 *len += (long_u)STRLEN(y_ptr->y_array[i]) + eolsize;
2116
2117 // Don't want newline character at end of last line if we're in MCHAR mode.
2118 if (y_ptr->y_type == MCHAR && *len >= eolsize)
2119 *len -= eolsize;
2120
2121 p = *str = alloc(*len + 1); // add one to avoid zero
2122 if (p == NULL)
2123 return -1;
2124 lnum = 0;
2125 for (i = 0, j = 0; i < (int)*len; i++, j++)
2126 {
2127 if (y_ptr->y_array[lnum][j] == '\n')
2128 p[i] = NUL;
2129 else if (y_ptr->y_array[lnum][j] == NUL)
2130 {
2131 # ifdef USE_CRNL
2132 p[i++] = '\r';
2133 # endif
2134 p[i] = '\n';
2135 lnum++;
2136 j = -1;
2137 }
2138 else
2139 p[i] = y_ptr->y_array[lnum][j];
2140 }
2141 return y_ptr->y_type;
2142 }
2143
2144 /*
2145 * When "regname" is a clipboard register, obtain the selection. If it's not
2146 * available return zero, otherwise return "regname".
2147 */
2148 int
2149 may_get_selection(int regname)
2150 {
2151 if (regname == '*')
2152 {
2153 if (!clip_star.available)
2154 regname = 0;
2155 else
2156 clip_get_selection(&clip_star);
2157 }
2158 else if (regname == '+')
2159 {
2160 if (!clip_plus.available)
2161 regname = 0;
2162 else
2163 clip_get_selection(&clip_plus);
2164 }
2165 return regname;
2166 }
2167
2168 /*
2169 * If we have written to a clipboard register, send the text to the clipboard.
2170 */
2171 void
2172 may_set_selection(void)
2173 {
2174 if ((get_y_current() == get_y_register(STAR_REGISTER))
2175 && clip_star.available)
2176 {
2177 clip_own_selection(&clip_star);
2178 clip_gen_set_selection(&clip_star);
2179 }
2180 else if ((get_y_current() == get_y_register(PLUS_REGISTER))
2181 && clip_plus.available)
2182 {
2183 clip_own_selection(&clip_plus);
2184 clip_gen_set_selection(&clip_plus);
2185 }
2186 }
2187
2188 /*
2189 * Adjust the register name pointed to with "rp" for the clipboard being
2190 * used always and the clipboard being available.
2191 */
2192 void
2193 adjust_clip_reg(int *rp)
2194 {
2195 // If no reg. specified, and "unnamed" or "unnamedplus" is in 'clipboard',
2196 // use '*' or '+' reg, respectively. "unnamedplus" prevails.
2197 if (*rp == 0 && (clip_unnamed != 0 || clip_unnamed_saved != 0))
2198 {
2199 if (clip_unnamed != 0)
2200 *rp = ((clip_unnamed & CLIP_UNNAMED_PLUS) && clip_plus.available)
2201 ? '+' : '*';
2202 else
2203 *rp = ((clip_unnamed_saved & CLIP_UNNAMED_PLUS)
2204 && clip_plus.available) ? '+' : '*';
2205 }
2206 if (!clip_star.available && *rp == '*')
2207 *rp = 0;
2208 if (!clip_plus.available && *rp == '+')
2209 *rp = 0;
2210 }
2211
2212 #endif // FEAT_CLIPBOARD