blob: 3084ce187193fc599d507b63bc9f5671f3fb7330 [file] [log] [blame]
Bram Moolenaar45fffdf2020-03-24 21:42:01 +01001/* 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
46clip_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
75clip_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
110clip_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
125clip_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
161clip_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
176clip_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
214clip_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 */
232static int global_change_count = 0; // if set, inside a start_global_changes
233static int clipboard_needs_update = FALSE; // clipboard needs to be updated
234static int clip_did_set_selection = TRUE;
235
236/*
237 * Save clip_unnamed and reset it.
238 */
239 void
240start_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
259is_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
268end_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
301clip_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
314clip_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
328clip_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
346clip_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
369clip_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
421clip_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
490clip_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
525clip_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
558clip_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
601clip_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
623clip_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
724clip_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
906clip_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
929clip_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
944clip_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
957clip_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
988clip_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
1184clip_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
1210clip_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
1227clip_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
1235clip_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 *
1255check_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 {
Bram Moolenaar07188fc2020-06-05 20:03:16 +02001320 if (global_busy)
1321 // clip_unnamed will be reset to clip_unnamed_saved
1322 // at end_global_changes
1323 clip_unnamed_saved = new_unnamed;
1324 else
1325 clip_unnamed = new_unnamed;
Bram Moolenaar45fffdf2020-03-24 21:42:01 +01001326 clip_autoselect_star = new_autoselect_star;
1327 clip_autoselect_plus = new_autoselect_plus;
1328 clip_autoselectml = new_autoselectml;
1329 clip_html = new_html;
1330 vim_regfree(clip_exclude_prog);
1331 clip_exclude_prog = new_exclude_prog;
1332#ifdef FEAT_GUI_GTK
1333 if (gui.in_use)
1334 {
1335 gui_gtk_set_selection_targets();
1336 gui_gtk_set_dnd_targets();
1337 }
1338#endif
1339 }
1340 else
1341 vim_regfree(new_exclude_prog);
1342
1343 return errmsg;
1344}
1345
1346/*
1347 * Stuff for the X clipboard. Shared between VMS and Unix.
1348 */
1349
1350#if defined(FEAT_XCLIPBOARD) || defined(FEAT_GUI_X11) || defined(PROTO)
1351# include <X11/Xatom.h>
1352# include <X11/Intrinsic.h>
1353
1354/*
1355 * Open the application context (if it hasn't been opened yet).
1356 * Used for Motif and Athena GUI and the xterm clipboard.
1357 */
1358 void
1359open_app_context(void)
1360{
1361 if (app_context == NULL)
1362 {
1363 XtToolkitInitialize();
1364 app_context = XtCreateApplicationContext();
1365 }
1366}
1367
1368static Atom vim_atom; // Vim's own special selection format
1369static Atom vimenc_atom; // Vim's extended selection format
1370static Atom utf8_atom;
1371static Atom compound_text_atom;
1372static Atom text_atom;
1373static Atom targets_atom;
1374static Atom timestamp_atom; // Used to get a timestamp
1375
1376 void
1377x11_setup_atoms(Display *dpy)
1378{
1379 vim_atom = XInternAtom(dpy, VIM_ATOM_NAME, False);
1380 vimenc_atom = XInternAtom(dpy, VIMENC_ATOM_NAME,False);
1381 utf8_atom = XInternAtom(dpy, "UTF8_STRING", False);
1382 compound_text_atom = XInternAtom(dpy, "COMPOUND_TEXT", False);
1383 text_atom = XInternAtom(dpy, "TEXT", False);
1384 targets_atom = XInternAtom(dpy, "TARGETS", False);
1385 clip_star.sel_atom = XA_PRIMARY;
1386 clip_plus.sel_atom = XInternAtom(dpy, "CLIPBOARD", False);
1387 timestamp_atom = XInternAtom(dpy, "TIMESTAMP", False);
1388}
1389
1390/*
1391 * X Selection stuff, for cutting and pasting text to other windows.
1392 */
1393
1394 static Boolean
1395clip_x11_convert_selection_cb(
1396 Widget w UNUSED,
1397 Atom *sel_atom,
1398 Atom *target,
1399 Atom *type,
1400 XtPointer *value,
1401 long_u *length,
1402 int *format)
1403{
1404 static char_u *save_result = NULL;
1405 static long_u save_length = 0;
1406 char_u *string;
1407 int motion_type;
1408 Clipboard_T *cbd;
1409 int i;
1410
1411 if (*sel_atom == clip_plus.sel_atom)
1412 cbd = &clip_plus;
1413 else
1414 cbd = &clip_star;
1415
1416 if (!cbd->owned)
1417 return False; // Shouldn't ever happen
1418
1419 // requestor wants to know what target types we support
1420 if (*target == targets_atom)
1421 {
1422 static Atom array[7];
1423
1424 *value = (XtPointer)array;
1425 i = 0;
1426 array[i++] = targets_atom;
1427 array[i++] = vimenc_atom;
1428 array[i++] = vim_atom;
1429 if (enc_utf8)
1430 array[i++] = utf8_atom;
1431 array[i++] = XA_STRING;
1432 array[i++] = text_atom;
1433 array[i++] = compound_text_atom;
1434
1435 *type = XA_ATOM;
1436 // This used to be: *format = sizeof(Atom) * 8; but that caused
1437 // crashes on 64 bit machines. (Peter Derr)
1438 *format = 32;
1439 *length = i;
1440 return True;
1441 }
1442
1443 if ( *target != XA_STRING
1444 && *target != vimenc_atom
1445 && (*target != utf8_atom || !enc_utf8)
1446 && *target != vim_atom
1447 && *target != text_atom
1448 && *target != compound_text_atom)
1449 return False;
1450
1451 clip_get_selection(cbd);
1452 motion_type = clip_convert_selection(&string, length, cbd);
1453 if (motion_type < 0)
1454 return False;
1455
1456 // For our own format, the first byte contains the motion type
1457 if (*target == vim_atom)
1458 (*length)++;
1459
1460 // Our own format with encoding: motion 'encoding' NUL text
1461 if (*target == vimenc_atom)
1462 *length += STRLEN(p_enc) + 2;
1463
1464 if (save_length < *length || save_length / 2 >= *length)
1465 *value = XtRealloc((char *)save_result, (Cardinal)*length + 1);
1466 else
1467 *value = save_result;
1468 if (*value == NULL)
1469 {
1470 vim_free(string);
1471 return False;
1472 }
1473 save_result = (char_u *)*value;
1474 save_length = *length;
1475
1476 if (*target == XA_STRING || (*target == utf8_atom && enc_utf8))
1477 {
1478 mch_memmove(save_result, string, (size_t)(*length));
1479 *type = *target;
1480 }
1481 else if (*target == compound_text_atom || *target == text_atom)
1482 {
1483 XTextProperty text_prop;
1484 char *string_nt = (char *)save_result;
1485 int conv_result;
1486
1487 // create NUL terminated string which XmbTextListToTextProperty wants
1488 mch_memmove(string_nt, string, (size_t)*length);
1489 string_nt[*length] = NUL;
1490 conv_result = XmbTextListToTextProperty(X_DISPLAY, (char **)&string_nt,
1491 1, XCompoundTextStyle, &text_prop);
1492 if (conv_result != Success)
1493 {
1494 vim_free(string);
1495 return False;
1496 }
1497 *value = (XtPointer)(text_prop.value); // from plain text
1498 *length = text_prop.nitems;
1499 *type = compound_text_atom;
1500 XtFree((char *)save_result);
1501 save_result = (char_u *)*value;
1502 save_length = *length;
1503 }
1504 else if (*target == vimenc_atom)
1505 {
1506 int l = STRLEN(p_enc);
1507
1508 save_result[0] = motion_type;
1509 STRCPY(save_result + 1, p_enc);
1510 mch_memmove(save_result + l + 2, string, (size_t)(*length - l - 2));
1511 *type = vimenc_atom;
1512 }
1513 else
1514 {
1515 save_result[0] = motion_type;
1516 mch_memmove(save_result + 1, string, (size_t)(*length - 1));
1517 *type = vim_atom;
1518 }
1519 *format = 8; // 8 bits per char
1520 vim_free(string);
1521 return True;
1522}
1523
1524 static void
1525clip_x11_lose_ownership_cb(Widget w UNUSED, Atom *sel_atom)
1526{
1527 if (*sel_atom == clip_plus.sel_atom)
1528 clip_lose_selection(&clip_plus);
1529 else
1530 clip_lose_selection(&clip_star);
1531}
1532
1533 static void
1534clip_x11_notify_cb(Widget w UNUSED, Atom *sel_atom UNUSED, Atom *target UNUSED)
1535{
1536 // To prevent automatically freeing the selection value.
1537}
1538
1539/*
1540 * Property callback to get a timestamp for XtOwnSelection.
1541 */
1542 static void
1543clip_x11_timestamp_cb(
1544 Widget w,
1545 XtPointer n UNUSED,
1546 XEvent *event,
1547 Boolean *cont UNUSED)
1548{
1549 Atom actual_type;
1550 int format;
1551 unsigned long nitems, bytes_after;
1552 unsigned char *prop=NULL;
1553 XPropertyEvent *xproperty=&event->xproperty;
1554
1555 // Must be a property notify, state can't be Delete (True), has to be
1556 // one of the supported selection types.
1557 if (event->type != PropertyNotify || xproperty->state
1558 || (xproperty->atom != clip_star.sel_atom
1559 && xproperty->atom != clip_plus.sel_atom))
1560 return;
1561
1562 if (XGetWindowProperty(xproperty->display, xproperty->window,
1563 xproperty->atom, 0, 0, False, timestamp_atom, &actual_type, &format,
1564 &nitems, &bytes_after, &prop))
1565 return;
1566
1567 if (prop)
1568 XFree(prop);
1569
1570 // Make sure the property type is "TIMESTAMP" and it's 32 bits.
1571 if (actual_type != timestamp_atom || format != 32)
1572 return;
1573
1574 // Get the selection, using the event timestamp.
1575 if (XtOwnSelection(w, xproperty->atom, xproperty->time,
1576 clip_x11_convert_selection_cb, clip_x11_lose_ownership_cb,
1577 clip_x11_notify_cb) == OK)
1578 {
1579 // Set the "owned" flag now, there may have been a call to
1580 // lose_ownership_cb in between.
1581 if (xproperty->atom == clip_plus.sel_atom)
1582 clip_plus.owned = TRUE;
1583 else
1584 clip_star.owned = TRUE;
1585 }
1586}
1587
1588 void
1589x11_setup_selection(Widget w)
1590{
1591 XtAddEventHandler(w, PropertyChangeMask, False,
1592 /*(XtEventHandler)*/clip_x11_timestamp_cb, (XtPointer)NULL);
1593}
1594
1595 static void
1596clip_x11_request_selection_cb(
1597 Widget w UNUSED,
1598 XtPointer success,
1599 Atom *sel_atom,
1600 Atom *type,
1601 XtPointer value,
1602 long_u *length,
1603 int *format)
1604{
1605 int motion_type = MAUTO;
1606 long_u len;
1607 char_u *p;
1608 char **text_list = NULL;
1609 Clipboard_T *cbd;
1610 char_u *tmpbuf = NULL;
1611
1612 if (*sel_atom == clip_plus.sel_atom)
1613 cbd = &clip_plus;
1614 else
1615 cbd = &clip_star;
1616
1617 if (value == NULL || *length == 0)
1618 {
1619 clip_free_selection(cbd); // nothing received, clear register
1620 *(int *)success = FALSE;
1621 return;
1622 }
1623 p = (char_u *)value;
1624 len = *length;
1625 if (*type == vim_atom)
1626 {
1627 motion_type = *p++;
1628 len--;
1629 }
1630
1631 else if (*type == vimenc_atom)
1632 {
1633 char_u *enc;
1634 vimconv_T conv;
1635 int convlen;
1636
1637 motion_type = *p++;
1638 --len;
1639
1640 enc = p;
1641 p += STRLEN(p) + 1;
1642 len -= p - enc;
1643
1644 // If the encoding of the text is different from 'encoding', attempt
1645 // converting it.
1646 conv.vc_type = CONV_NONE;
1647 convert_setup(&conv, enc, p_enc);
1648 if (conv.vc_type != CONV_NONE)
1649 {
1650 convlen = len; // Need to use an int here.
1651 tmpbuf = string_convert(&conv, p, &convlen);
1652 len = convlen;
1653 if (tmpbuf != NULL)
1654 p = tmpbuf;
1655 convert_setup(&conv, NULL, NULL);
1656 }
1657 }
1658
1659 else if (*type == compound_text_atom
1660 || *type == utf8_atom
1661 || (enc_dbcs != 0 && *type == text_atom))
1662 {
1663 XTextProperty text_prop;
1664 int n_text = 0;
1665 int status;
1666
1667 text_prop.value = (unsigned char *)value;
1668 text_prop.encoding = *type;
1669 text_prop.format = *format;
1670 text_prop.nitems = len;
1671#if defined(X_HAVE_UTF8_STRING)
1672 if (*type == utf8_atom)
1673 status = Xutf8TextPropertyToTextList(X_DISPLAY, &text_prop,
1674 &text_list, &n_text);
1675 else
1676#endif
1677 status = XmbTextPropertyToTextList(X_DISPLAY, &text_prop,
1678 &text_list, &n_text);
1679 if (status != Success || n_text < 1)
1680 {
1681 *(int *)success = FALSE;
1682 return;
1683 }
1684 p = (char_u *)text_list[0];
1685 len = STRLEN(p);
1686 }
1687 clip_yank_selection(motion_type, p, (long)len, cbd);
1688
1689 if (text_list != NULL)
1690 XFreeStringList(text_list);
1691 vim_free(tmpbuf);
1692 XtFree((char *)value);
1693 *(int *)success = TRUE;
1694}
1695
1696 void
1697clip_x11_request_selection(
1698 Widget myShell,
1699 Display *dpy,
1700 Clipboard_T *cbd)
1701{
1702 XEvent event;
1703 Atom type;
1704 static int success;
1705 int i;
1706 time_t start_time;
1707 int timed_out = FALSE;
1708
1709 for (i = 0; i < 6; i++)
1710 {
1711 switch (i)
1712 {
1713 case 0: type = vimenc_atom; break;
1714 case 1: type = vim_atom; break;
1715 case 2: type = utf8_atom; break;
1716 case 3: type = compound_text_atom; break;
1717 case 4: type = text_atom; break;
1718 default: type = XA_STRING;
1719 }
1720 if (type == utf8_atom
1721# if defined(X_HAVE_UTF8_STRING)
1722 && !enc_utf8
1723# endif
1724 )
1725 // Only request utf-8 when 'encoding' is utf8 and
1726 // Xutf8TextPropertyToTextList is available.
1727 continue;
1728 success = MAYBE;
1729 XtGetSelectionValue(myShell, cbd->sel_atom, type,
1730 clip_x11_request_selection_cb, (XtPointer)&success, CurrentTime);
1731
1732 // Make sure the request for the selection goes out before waiting for
1733 // a response.
1734 XFlush(dpy);
1735
1736 /*
1737 * Wait for result of selection request, otherwise if we type more
1738 * characters, then they will appear before the one that requested the
1739 * paste! Don't worry, we will catch up with any other events later.
1740 */
1741 start_time = time(NULL);
1742 while (success == MAYBE)
1743 {
1744 if (XCheckTypedEvent(dpy, PropertyNotify, &event)
1745 || XCheckTypedEvent(dpy, SelectionNotify, &event)
1746 || XCheckTypedEvent(dpy, SelectionRequest, &event))
1747 {
1748 // This is where clip_x11_request_selection_cb() should be
1749 // called. It may actually happen a bit later, so we loop
1750 // until "success" changes.
1751 // We may get a SelectionRequest here and if we don't handle
1752 // it we hang. KDE klipper does this, for example.
1753 // We need to handle a PropertyNotify for large selections.
1754 XtDispatchEvent(&event);
1755 continue;
1756 }
1757
1758 // Time out after 2 to 3 seconds to avoid that we hang when the
1759 // other process doesn't respond. Note that the SelectionNotify
1760 // event may still come later when the selection owner comes back
1761 // to life and the text gets inserted unexpectedly. Don't know
1762 // why that happens or how to avoid that :-(.
1763 if (time(NULL) > start_time + 2)
1764 {
1765 timed_out = TRUE;
1766 break;
1767 }
1768
1769 // Do we need this? Probably not.
1770 XSync(dpy, False);
1771
1772 // Wait for 1 msec to avoid that we eat up all CPU time.
1773 ui_delay(1L, TRUE);
1774 }
1775
1776 if (success == TRUE)
1777 return;
1778
1779 // don't do a retry with another type after timing out, otherwise we
1780 // hang for 15 seconds.
1781 if (timed_out)
1782 break;
1783 }
1784
1785 // Final fallback position - use the X CUT_BUFFER0 store
1786 yank_cut_buffer0(dpy, cbd);
1787}
1788
1789 void
1790clip_x11_lose_selection(Widget myShell, Clipboard_T *cbd)
1791{
1792 XtDisownSelection(myShell, cbd->sel_atom,
1793 XtLastTimestampProcessed(XtDisplay(myShell)));
1794}
1795
1796 int
1797clip_x11_own_selection(Widget myShell, Clipboard_T *cbd)
1798{
1799 // When using the GUI we have proper timestamps, use the one of the last
1800 // event. When in the console we don't get events (the terminal gets
1801 // them), Get the time by a zero-length append, clip_x11_timestamp_cb will
1802 // be called with the current timestamp.
1803#ifdef FEAT_GUI
1804 if (gui.in_use)
1805 {
1806 if (XtOwnSelection(myShell, cbd->sel_atom,
1807 XtLastTimestampProcessed(XtDisplay(myShell)),
1808 clip_x11_convert_selection_cb, clip_x11_lose_ownership_cb,
1809 clip_x11_notify_cb) == False)
1810 return FAIL;
1811 }
1812 else
1813#endif
1814 {
1815 if (!XChangeProperty(XtDisplay(myShell), XtWindow(myShell),
1816 cbd->sel_atom, timestamp_atom, 32, PropModeAppend, NULL, 0))
1817 return FAIL;
1818 }
1819 // Flush is required in a terminal as nothing else is doing it.
1820 XFlush(XtDisplay(myShell));
1821 return OK;
1822}
1823
1824/*
1825 * Send the current selection to the clipboard. Do nothing for X because we
1826 * will fill in the selection only when requested by another app.
1827 */
1828 void
1829clip_x11_set_selection(Clipboard_T *cbd UNUSED)
1830{
1831}
1832
1833#endif
1834
1835#if defined(FEAT_XCLIPBOARD) || defined(FEAT_GUI_X11) \
1836 || defined(FEAT_GUI_GTK) || defined(PROTO)
1837/*
1838 * Get the contents of the X CUT_BUFFER0 and put it in "cbd".
1839 */
1840 void
1841yank_cut_buffer0(Display *dpy, Clipboard_T *cbd)
1842{
1843 int nbytes = 0;
1844 char_u *buffer = (char_u *)XFetchBuffer(dpy, &nbytes, 0);
1845
1846 if (nbytes > 0)
1847 {
1848 int done = FALSE;
1849
1850 // CUT_BUFFER0 is supposed to be always latin1. Convert to 'enc' when
1851 // using a multi-byte encoding. Conversion between two 8-bit
1852 // character sets usually fails and the text might actually be in
1853 // 'enc' anyway.
1854 if (has_mbyte)
1855 {
1856 char_u *conv_buf;
1857 vimconv_T vc;
1858
1859 vc.vc_type = CONV_NONE;
1860 if (convert_setup(&vc, (char_u *)"latin1", p_enc) == OK)
1861 {
1862 conv_buf = string_convert(&vc, buffer, &nbytes);
1863 if (conv_buf != NULL)
1864 {
1865 clip_yank_selection(MCHAR, conv_buf, (long)nbytes, cbd);
1866 vim_free(conv_buf);
1867 done = TRUE;
1868 }
1869 convert_setup(&vc, NULL, NULL);
1870 }
1871 }
1872 if (!done) // use the text without conversion
1873 clip_yank_selection(MCHAR, buffer, (long)nbytes, cbd);
1874 XFree((void *)buffer);
1875 if (p_verbose > 0)
1876 {
1877 verbose_enter();
1878 verb_msg(_("Used CUT_BUFFER0 instead of empty selection"));
1879 verbose_leave();
1880 }
1881 }
1882}
1883#endif
1884
1885/*
1886 * SELECTION / PRIMARY ('*')
1887 *
1888 * Text selection stuff that uses the GUI selection register '*'. When using a
1889 * GUI this may be text from another window, otherwise it is the last text we
1890 * had highlighted with VIsual mode. With mouse support, clicking the middle
1891 * button performs the paste, otherwise you will need to do <"*p>. "
1892 * If not under X, it is synonymous with the clipboard register '+'.
1893 *
1894 * X CLIPBOARD ('+')
1895 *
1896 * Text selection stuff that uses the GUI clipboard register '+'.
1897 * Under X, this matches the standard cut/paste buffer CLIPBOARD selection.
1898 * It will be used for unnamed cut/pasting is 'clipboard' contains "unnamed",
1899 * otherwise you will need to do <"+p>. "
1900 * If not under X, it is synonymous with the selection register '*'.
1901 */
1902
1903/*
1904 * Routine to export any final X selection we had to the environment
1905 * so that the text is still available after Vim has exited. X selections
1906 * only exist while the owning application exists, so we write to the
1907 * permanent (while X runs) store CUT_BUFFER0.
1908 * Dump the CLIPBOARD selection if we own it (it's logically the more
1909 * 'permanent' of the two), otherwise the PRIMARY one.
1910 * For now, use a hard-coded sanity limit of 1Mb of data.
1911 */
1912#if (defined(FEAT_X11) && defined(FEAT_CLIPBOARD)) || defined(PROTO)
1913 void
1914x11_export_final_selection(void)
1915{
1916 Display *dpy;
1917 char_u *str = NULL;
1918 long_u len = 0;
1919 int motion_type = -1;
1920
1921# ifdef FEAT_GUI
1922 if (gui.in_use)
1923 dpy = X_DISPLAY;
1924 else
1925# endif
1926# ifdef FEAT_XCLIPBOARD
1927 dpy = xterm_dpy;
1928# else
1929 return;
1930# endif
1931
1932 // Get selection to export
1933 if (clip_plus.owned)
1934 motion_type = clip_convert_selection(&str, &len, &clip_plus);
1935 else if (clip_star.owned)
1936 motion_type = clip_convert_selection(&str, &len, &clip_star);
1937
1938 // Check it's OK
1939 if (dpy != NULL && str != NULL && motion_type >= 0
1940 && len < 1024*1024 && len > 0)
1941 {
1942 int ok = TRUE;
1943
1944 // The CUT_BUFFER0 is supposed to always contain latin1. Convert from
1945 // 'enc' when it is a multi-byte encoding. When 'enc' is an 8-bit
1946 // encoding conversion usually doesn't work, so keep the text as-is.
1947 if (has_mbyte)
1948 {
1949 vimconv_T vc;
1950
1951 vc.vc_type = CONV_NONE;
1952 if (convert_setup(&vc, p_enc, (char_u *)"latin1") == OK)
1953 {
1954 int intlen = len;
1955 char_u *conv_str;
1956
1957 vc.vc_fail = TRUE;
1958 conv_str = string_convert(&vc, str, &intlen);
1959 len = intlen;
1960 if (conv_str != NULL)
1961 {
1962 vim_free(str);
1963 str = conv_str;
1964 }
1965 else
1966 {
1967 ok = FALSE;
1968 }
1969 convert_setup(&vc, NULL, NULL);
1970 }
1971 else
1972 {
1973 ok = FALSE;
1974 }
1975 }
1976
1977 // Do not store the string if conversion failed. Better to use any
1978 // other selection than garbled text.
1979 if (ok)
1980 {
1981 XStoreBuffer(dpy, (char *)str, (int)len, 0);
1982 XFlush(dpy);
1983 }
1984 }
1985
1986 vim_free(str);
1987}
1988#endif
1989
1990 void
1991clip_free_selection(Clipboard_T *cbd)
1992{
1993 yankreg_T *y_ptr = get_y_current();
1994
1995 if (cbd == &clip_plus)
1996 set_y_current(get_y_register(PLUS_REGISTER));
1997 else
1998 set_y_current(get_y_register(STAR_REGISTER));
1999 free_yank_all();
2000 get_y_current()->y_size = 0;
2001 set_y_current(y_ptr);
2002}
2003
2004/*
2005 * Get the selected text and put it in register '*' or '+'.
2006 */
2007 void
2008clip_get_selection(Clipboard_T *cbd)
2009{
2010 yankreg_T *old_y_previous, *old_y_current;
2011 pos_T old_cursor;
2012 pos_T old_visual;
2013 int old_visual_mode;
2014 colnr_T old_curswant;
2015 int old_set_curswant;
2016 pos_T old_op_start, old_op_end;
2017 oparg_T oa;
2018 cmdarg_T ca;
2019
2020 if (cbd->owned)
2021 {
2022 if ((cbd == &clip_plus
2023 && get_y_register(PLUS_REGISTER)->y_array != NULL)
2024 || (cbd == &clip_star
2025 && get_y_register(STAR_REGISTER)->y_array != NULL))
2026 return;
2027
Bram Moolenaarfccbf062020-11-26 20:34:00 +01002028 // Avoid triggering autocmds such as TextYankPost.
2029 block_autocmds();
2030
Bram Moolenaar45fffdf2020-03-24 21:42:01 +01002031 // Get the text between clip_star.start & clip_star.end
2032 old_y_previous = get_y_previous();
2033 old_y_current = get_y_current();
2034 old_cursor = curwin->w_cursor;
2035 old_curswant = curwin->w_curswant;
2036 old_set_curswant = curwin->w_set_curswant;
2037 old_op_start = curbuf->b_op_start;
2038 old_op_end = curbuf->b_op_end;
2039 old_visual = VIsual;
2040 old_visual_mode = VIsual_mode;
2041 clear_oparg(&oa);
2042 oa.regname = (cbd == &clip_plus ? '+' : '*');
2043 oa.op_type = OP_YANK;
Bram Moolenaara80faa82020-04-12 19:37:17 +02002044 CLEAR_FIELD(ca);
Bram Moolenaar45fffdf2020-03-24 21:42:01 +01002045 ca.oap = &oa;
2046 ca.cmdchar = 'y';
2047 ca.count1 = 1;
2048 ca.retval = CA_NO_ADJ_OP_END;
2049 do_pending_operator(&ca, 0, TRUE);
2050 set_y_previous(old_y_previous);
2051 set_y_current(old_y_current);
2052 curwin->w_cursor = old_cursor;
2053 changed_cline_bef_curs(); // need to update w_virtcol et al
2054 curwin->w_curswant = old_curswant;
2055 curwin->w_set_curswant = old_set_curswant;
2056 curbuf->b_op_start = old_op_start;
2057 curbuf->b_op_end = old_op_end;
2058 VIsual = old_visual;
2059 VIsual_mode = old_visual_mode;
Bram Moolenaarfccbf062020-11-26 20:34:00 +01002060
2061 unblock_autocmds();
Bram Moolenaar45fffdf2020-03-24 21:42:01 +01002062 }
2063 else if (!is_clipboard_needs_update())
2064 {
2065 clip_free_selection(cbd);
2066
2067 // Try to get selected text from another window
2068 clip_gen_request_selection(cbd);
2069 }
2070}
2071
2072/*
2073 * Convert from the GUI selection string into the '*'/'+' register.
2074 */
2075 void
2076clip_yank_selection(
2077 int type,
2078 char_u *str,
2079 long len,
2080 Clipboard_T *cbd)
2081{
2082 yankreg_T *y_ptr;
2083
2084 if (cbd == &clip_plus)
2085 y_ptr = get_y_register(PLUS_REGISTER);
2086 else
2087 y_ptr = get_y_register(STAR_REGISTER);
2088
2089 clip_free_selection(cbd);
2090
2091 str_to_reg(y_ptr, type, str, len, 0L, FALSE);
2092}
2093
2094/*
2095 * Convert the '*'/'+' register into a GUI selection string returned in *str
2096 * with length *len.
2097 * Returns the motion type, or -1 for failure.
2098 */
2099 int
2100clip_convert_selection(char_u **str, long_u *len, Clipboard_T *cbd)
2101{
2102 char_u *p;
2103 int lnum;
2104 int i, j;
2105 int_u eolsize;
2106 yankreg_T *y_ptr;
2107
2108 if (cbd == &clip_plus)
2109 y_ptr = get_y_register(PLUS_REGISTER);
2110 else
2111 y_ptr = get_y_register(STAR_REGISTER);
2112
2113# ifdef USE_CRNL
2114 eolsize = 2;
2115# else
2116 eolsize = 1;
2117# endif
2118
2119 *str = NULL;
2120 *len = 0;
2121 if (y_ptr->y_array == NULL)
2122 return -1;
2123
2124 for (i = 0; i < y_ptr->y_size; i++)
2125 *len += (long_u)STRLEN(y_ptr->y_array[i]) + eolsize;
2126
2127 // Don't want newline character at end of last line if we're in MCHAR mode.
2128 if (y_ptr->y_type == MCHAR && *len >= eolsize)
2129 *len -= eolsize;
2130
2131 p = *str = alloc(*len + 1); // add one to avoid zero
2132 if (p == NULL)
2133 return -1;
2134 lnum = 0;
2135 for (i = 0, j = 0; i < (int)*len; i++, j++)
2136 {
2137 if (y_ptr->y_array[lnum][j] == '\n')
2138 p[i] = NUL;
2139 else if (y_ptr->y_array[lnum][j] == NUL)
2140 {
2141# ifdef USE_CRNL
2142 p[i++] = '\r';
2143# endif
2144 p[i] = '\n';
2145 lnum++;
2146 j = -1;
2147 }
2148 else
2149 p[i] = y_ptr->y_array[lnum][j];
2150 }
2151 return y_ptr->y_type;
2152}
2153
2154/*
2155 * When "regname" is a clipboard register, obtain the selection. If it's not
2156 * available return zero, otherwise return "regname".
2157 */
2158 int
2159may_get_selection(int regname)
2160{
2161 if (regname == '*')
2162 {
2163 if (!clip_star.available)
2164 regname = 0;
2165 else
2166 clip_get_selection(&clip_star);
2167 }
2168 else if (regname == '+')
2169 {
2170 if (!clip_plus.available)
2171 regname = 0;
2172 else
2173 clip_get_selection(&clip_plus);
2174 }
2175 return regname;
2176}
2177
2178/*
2179 * If we have written to a clipboard register, send the text to the clipboard.
2180 */
2181 void
2182may_set_selection(void)
2183{
2184 if ((get_y_current() == get_y_register(STAR_REGISTER))
2185 && clip_star.available)
2186 {
2187 clip_own_selection(&clip_star);
2188 clip_gen_set_selection(&clip_star);
2189 }
2190 else if ((get_y_current() == get_y_register(PLUS_REGISTER))
2191 && clip_plus.available)
2192 {
2193 clip_own_selection(&clip_plus);
2194 clip_gen_set_selection(&clip_plus);
2195 }
2196}
2197
2198/*
2199 * Adjust the register name pointed to with "rp" for the clipboard being
2200 * used always and the clipboard being available.
2201 */
2202 void
2203adjust_clip_reg(int *rp)
2204{
2205 // If no reg. specified, and "unnamed" or "unnamedplus" is in 'clipboard',
2206 // use '*' or '+' reg, respectively. "unnamedplus" prevails.
2207 if (*rp == 0 && (clip_unnamed != 0 || clip_unnamed_saved != 0))
2208 {
2209 if (clip_unnamed != 0)
2210 *rp = ((clip_unnamed & CLIP_UNNAMED_PLUS) && clip_plus.available)
2211 ? '+' : '*';
2212 else
2213 *rp = ((clip_unnamed_saved & CLIP_UNNAMED_PLUS)
2214 && clip_plus.available) ? '+' : '*';
2215 }
2216 if (!clip_star.available && *rp == '*')
2217 *rp = 0;
2218 if (!clip_plus.available && *rp == '+')
2219 *rp = 0;
2220}
2221
2222#endif // FEAT_CLIPBOARD