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