xref: /vim-8.2.3635/src/gui.c (revision d2ea7cf1)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved		by Bram Moolenaar
4  *				GUI/Motif support by Robert Webb
5  *
6  * Do ":help uganda"  in Vim to read copying and usage conditions.
7  * Do ":help credits" in Vim to see a list of people who contributed.
8  * See README.txt for an overview of the Vim source code.
9  */
10 
11 #include "vim.h"
12 
13 // Structure containing all the GUI information
14 gui_T gui;
15 
16 #if !defined(FEAT_GUI_GTK)
17 static void set_guifontwide(char_u *font_name);
18 #endif
19 static void gui_check_pos(void);
20 static void gui_reset_scroll_region(void);
21 static void gui_outstr(char_u *, int);
22 static int gui_screenchar(int off, int flags, guicolor_T fg, guicolor_T bg, int back);
23 static int gui_outstr_nowrap(char_u *s, int len, int flags, guicolor_T fg, guicolor_T bg, int back);
24 static void gui_delete_lines(int row, int count);
25 static void gui_insert_lines(int row, int count);
26 static int gui_xy2colrow(int x, int y, int *colp);
27 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
28 static int gui_has_tabline(void);
29 #endif
30 static void gui_do_scrollbar(win_T *wp, int which, int enable);
31 static void gui_update_horiz_scrollbar(int);
32 static void gui_set_fg_color(char_u *name);
33 static void gui_set_bg_color(char_u *name);
34 static win_T *xy2win(int x, int y, mouse_find_T popup);
35 
36 #ifdef GUI_MAY_FORK
37 static void gui_do_fork(void);
38 
39 static int gui_read_child_pipe(int fd);
40 
41 // Return values for gui_read_child_pipe
42 enum {
43     GUI_CHILD_IO_ERROR,
44     GUI_CHILD_OK,
45     GUI_CHILD_FAILED
46 };
47 #endif
48 
49 static void gui_attempt_start(void);
50 
51 static int can_update_cursor = TRUE; // can display the cursor
52 static int disable_flush = 0;	// If > 0, gui_mch_flush() is disabled.
53 
54 /*
55  * The Athena scrollbars can move the thumb to after the end of the scrollbar,
56  * this makes the thumb indicate the part of the text that is shown.  Motif
57  * can't do this.
58  */
59 #if defined(FEAT_GUI_ATHENA)
60 # define SCROLL_PAST_END
61 #endif
62 
63 /*
64  * gui_start -- Called when user wants to start the GUI.
65  *
66  * Careful: This function can be called recursively when there is a ":gui"
67  * command in the .gvimrc file.  Only the first call should fork, not the
68  * recursive call.
69  */
70     void
71 gui_start(char_u *arg UNUSED)
72 {
73     char_u	*old_term;
74     static int	recursive = 0;
75 #if defined(GUI_MAY_SPAWN) && defined(EXPERIMENTAL_GUI_CMD)
76     char	*msg = NULL;
77 #endif
78 
79     old_term = vim_strsave(T_NAME);
80 
81     settmode(TMODE_COOK);		// stop RAW mode
82     if (full_screen)
83 	cursor_on();			// needed for ":gui" in .vimrc
84     full_screen = FALSE;
85 
86     ++recursive;
87 
88 #ifdef GUI_MAY_FORK
89     /*
90      * Quit the current process and continue in the child.
91      * Makes "gvim file" disconnect from the shell it was started in.
92      * Don't do this when Vim was started with "-f" or the 'f' flag is present
93      * in 'guioptions'.
94      * Don't do this when there is a running job, we can only get the status
95      * of a child from the parent.
96      */
97     if (gui.dofork && !vim_strchr(p_go, GO_FORG) && recursive <= 1
98 # ifdef FEAT_JOB_CHANNEL
99 	    && !job_any_running()
100 # endif
101 	    )
102     {
103 	gui_do_fork();
104     }
105     else
106 #endif
107 #ifdef GUI_MAY_SPAWN
108     if (gui.dospawn
109 # ifdef EXPERIMENTAL_GUI_CMD
110 	    && gui.dofork
111 # endif
112 	    && !vim_strchr(p_go, GO_FORG)
113 	    && !anyBufIsChanged()
114 # ifdef FEAT_JOB_CHANNEL
115 	    && !job_any_running()
116 # endif
117 	    )
118     {
119 # ifdef EXPERIMENTAL_GUI_CMD
120 	msg =
121 # endif
122 	    gui_mch_do_spawn(arg);
123     }
124     else
125 #endif
126     {
127 #ifdef FEAT_GUI_GTK
128 	// If there is 'f' in 'guioptions' and specify -g argument,
129 	// gui_mch_init_check() was not called yet.
130 	if (gui_mch_init_check() != OK)
131 	    getout_preserve_modified(1);
132 #endif
133 	gui_attempt_start();
134     }
135 
136     if (!gui.in_use)			// failed to start GUI
137     {
138 	// Back to old term settings
139 	//
140 	// FIXME: If we got here because a child process failed and flagged to
141 	// the parent to resume, and X11 is enabled with FEAT_TITLE, this will
142 	// hit an X11 I/O error and do a longjmp(), leaving recursive
143 	// permanently set to 1. This is probably not as big a problem as it
144 	// sounds, because gui_mch_init() in both gui_x11.c and gui_gtk_x11.c
145 	// return "OK" unconditionally, so it would be very difficult to
146 	// actually hit this case.
147 	termcapinit(old_term);
148 	settmode(TMODE_RAW);		// restart RAW mode
149 #ifdef FEAT_TITLE
150 	set_title_defaults();		// set 'title' and 'icon' again
151 #endif
152 #if defined(GUI_MAY_SPAWN) && defined(EXPERIMENTAL_GUI_CMD)
153 	if (msg)
154 	    emsg(msg);
155 #endif
156     }
157 
158     vim_free(old_term);
159 
160     // If the GUI started successfully, trigger the GUIEnter event, otherwise
161     // the GUIFailed event.
162     gui_mch_update();
163     apply_autocmds(gui.in_use ? EVENT_GUIENTER : EVENT_GUIFAILED,
164 						   NULL, NULL, FALSE, curbuf);
165     --recursive;
166 }
167 
168 /*
169  * Set_termname() will call gui_init() to start the GUI.
170  * Set the "starting" flag, to indicate that the GUI will start.
171  *
172  * We don't want to open the GUI shell until after we've read .gvimrc,
173  * otherwise we don't know what font we will use, and hence we don't know
174  * what size the shell should be.  So if there are errors in the .gvimrc
175  * file, they will have to go to the terminal: Set full_screen to FALSE.
176  * full_screen will be set to TRUE again by a successful termcapinit().
177  */
178     static void
179 gui_attempt_start(void)
180 {
181     static int recursive = 0;
182 
183     ++recursive;
184     gui.starting = TRUE;
185 
186 #ifdef FEAT_GUI_GTK
187     gui.event_time = GDK_CURRENT_TIME;
188 #endif
189 
190     termcapinit((char_u *)"builtin_gui");
191     gui.starting = recursive - 1;
192 
193 #if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_X11)
194     if (gui.in_use)
195     {
196 # ifdef FEAT_EVAL
197 	Window	x11_window;
198 	Display	*x11_display;
199 
200 	if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
201 	    set_vim_var_nr(VV_WINDOWID, (long)x11_window);
202 # endif
203 
204 	// Display error messages in a dialog now.
205 	display_errors();
206     }
207 #endif
208     --recursive;
209 }
210 
211 #ifdef GUI_MAY_FORK
212 
213 // for waitpid()
214 # if defined(HAVE_SYS_WAIT_H) || defined(HAVE_UNION_WAIT)
215 #  include <sys/wait.h>
216 # endif
217 
218 /*
219  * Create a new process, by forking. In the child, start the GUI, and in
220  * the parent, exit.
221  *
222  * If something goes wrong, this will return with gui.in_use still set
223  * to FALSE, in which case the caller should continue execution without
224  * the GUI.
225  *
226  * If the child fails to start the GUI, then the child will exit and the
227  * parent will return. If the child succeeds, then the parent will exit
228  * and the child will return.
229  */
230     static void
231 gui_do_fork(void)
232 {
233     int		pipefd[2];	// pipe between parent and child
234     int		pipe_error;
235     int		status;
236     int		exit_status;
237     pid_t	pid = -1;
238 
239     // Setup a pipe between the child and the parent, so that the parent
240     // knows when the child has done the setsid() call and is allowed to
241     // exit.
242     pipe_error = (pipe(pipefd) < 0);
243     pid = fork();
244     if (pid < 0)	    // Fork error
245     {
246 	emsg(_("E851: Failed to create a new process for the GUI"));
247 	return;
248     }
249     else if (pid > 0)	    // Parent
250     {
251 	// Give the child some time to do the setsid(), otherwise the
252 	// exit() may kill the child too (when starting gvim from inside a
253 	// gvim).
254 	if (!pipe_error)
255 	{
256 	    // The read returns when the child closes the pipe (or when
257 	    // the child dies for some reason).
258 	    close(pipefd[1]);
259 	    status = gui_read_child_pipe(pipefd[0]);
260 	    if (status == GUI_CHILD_FAILED)
261 	    {
262 		// The child failed to start the GUI, so the caller must
263 		// continue. There may be more error information written
264 		// to stderr by the child.
265 # ifdef __NeXT__
266 		wait4(pid, &exit_status, 0, (struct rusage *)0);
267 # else
268 		waitpid(pid, &exit_status, 0);
269 # endif
270 		emsg(_("E852: The child process failed to start the GUI"));
271 		return;
272 	    }
273 	    else if (status == GUI_CHILD_IO_ERROR)
274 	    {
275 		pipe_error = TRUE;
276 	    }
277 	    // else GUI_CHILD_OK: parent exit
278 	}
279 
280 	if (pipe_error)
281 	    ui_delay(301L, TRUE);
282 
283 	// When swapping screens we may need to go to the next line, e.g.,
284 	// after a hit-enter prompt and using ":gui".
285 	if (newline_on_exit)
286 	    mch_errmsg("\r\n");
287 
288 	/*
289 	 * The parent must skip the normal exit() processing, the child
290 	 * will do it.  For example, GTK messes up signals when exiting.
291 	 */
292 	_exit(0);
293     }
294     // Child
295 
296 #ifdef FEAT_GUI_GTK
297     // Call gtk_init_check() here after fork(). See gui_init_check().
298     if (gui_mch_init_check() != OK)
299 	getout_preserve_modified(1);
300 #endif
301 
302 # if defined(HAVE_SETSID) || defined(HAVE_SETPGID)
303     /*
304      * Change our process group.  On some systems/shells a CTRL-C in the
305      * shell where Vim was started would otherwise kill gvim!
306      */
307 #  if defined(HAVE_SETSID)
308     (void)setsid();
309 #  else
310     (void)setpgid(0, 0);
311 #  endif
312 # endif
313     if (!pipe_error)
314 	close(pipefd[0]);
315 
316 # if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
317     // Tell the session manager our new PID
318     gui_mch_forked();
319 # endif
320 
321     // Try to start the GUI
322     gui_attempt_start();
323 
324     // Notify the parent
325     if (!pipe_error)
326     {
327 	if (gui.in_use)
328 	    write_eintr(pipefd[1], "ok", 3);
329 	else
330 	    write_eintr(pipefd[1], "fail", 5);
331 	close(pipefd[1]);
332     }
333 
334     // If we failed to start the GUI, exit now.
335     if (!gui.in_use)
336 	getout_preserve_modified(1);
337 }
338 
339 /*
340  * Read from a pipe assumed to be connected to the child process (this
341  * function is called from the parent).
342  * Return GUI_CHILD_OK if the child successfully started the GUI,
343  * GUY_CHILD_FAILED if the child failed, or GUI_CHILD_IO_ERROR if there was
344  * some other error.
345  *
346  * The file descriptor will be closed before the function returns.
347  */
348     static int
349 gui_read_child_pipe(int fd)
350 {
351     long	bytes_read;
352 #define READ_BUFFER_SIZE 10
353     char	buffer[READ_BUFFER_SIZE];
354 
355     bytes_read = read_eintr(fd, buffer, READ_BUFFER_SIZE - 1);
356 #undef READ_BUFFER_SIZE
357     close(fd);
358     if (bytes_read < 0)
359 	return GUI_CHILD_IO_ERROR;
360     buffer[bytes_read] = NUL;
361     if (strcmp(buffer, "ok") == 0)
362 	return GUI_CHILD_OK;
363     return GUI_CHILD_FAILED;
364 }
365 
366 #endif // GUI_MAY_FORK
367 
368 /*
369  * Call this when vim starts up, whether or not the GUI is started
370  */
371     void
372 gui_prepare(int *argc, char **argv)
373 {
374     gui.in_use = FALSE;		    // No GUI yet (maybe later)
375     gui.starting = FALSE;	    // No GUI yet (maybe later)
376     gui_mch_prepare(argc, argv);
377 }
378 
379 /*
380  * Try initializing the GUI and check if it can be started.
381  * Used from main() to check early if "vim -g" can start the GUI.
382  * Used from gui_init() to prepare for starting the GUI.
383  * Returns FAIL or OK.
384  */
385     int
386 gui_init_check(void)
387 {
388     static int result = MAYBE;
389 
390     if (result != MAYBE)
391     {
392 	if (result == FAIL)
393 	    emsg(_("E229: Cannot start the GUI"));
394 	return result;
395     }
396 
397     gui.shell_created = FALSE;
398     gui.dying = FALSE;
399     gui.in_focus = TRUE;		// so the guicursor setting works
400     gui.dragged_sb = SBAR_NONE;
401     gui.dragged_wp = NULL;
402     gui.pointer_hidden = FALSE;
403     gui.col = 0;
404     gui.row = 0;
405     gui.num_cols = Columns;
406     gui.num_rows = Rows;
407 
408     gui.cursor_is_valid = FALSE;
409     gui.scroll_region_top = 0;
410     gui.scroll_region_bot = Rows - 1;
411     gui.scroll_region_left = 0;
412     gui.scroll_region_right = Columns - 1;
413     gui.highlight_mask = HL_NORMAL;
414     gui.char_width = 1;
415     gui.char_height = 1;
416     gui.char_ascent = 0;
417     gui.border_width = 0;
418 
419     gui.norm_font = NOFONT;
420 #ifndef FEAT_GUI_GTK
421     gui.bold_font = NOFONT;
422     gui.ital_font = NOFONT;
423     gui.boldital_font = NOFONT;
424 # ifdef FEAT_XFONTSET
425     gui.fontset = NOFONTSET;
426 # endif
427 #endif
428     gui.wide_font = NOFONT;
429 #ifndef FEAT_GUI_GTK
430     gui.wide_bold_font = NOFONT;
431     gui.wide_ital_font = NOFONT;
432     gui.wide_boldital_font = NOFONT;
433 #endif
434 
435 #ifdef FEAT_MENU
436 # ifndef FEAT_GUI_GTK
437 #  ifdef FONTSET_ALWAYS
438     gui.menu_fontset = NOFONTSET;
439 #  else
440     gui.menu_font = NOFONT;
441 #  endif
442 # endif
443     gui.menu_is_active = TRUE;	    // default: include menu
444 # ifndef FEAT_GUI_GTK
445     gui.menu_height = MENU_DEFAULT_HEIGHT;
446     gui.menu_width = 0;
447 # endif
448 #endif
449 #if defined(FEAT_TOOLBAR) && (defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA) \
450 	|| defined(FEAT_GUI_HAIKU))
451     gui.toolbar_height = 0;
452 #endif
453 #if defined(FEAT_FOOTER) && defined(FEAT_GUI_MOTIF)
454     gui.footer_height = 0;
455 #endif
456 #ifdef FEAT_BEVAL_TIP
457     gui.tooltip_fontset = NOFONTSET;
458 #endif
459 
460     gui.scrollbar_width = gui.scrollbar_height = SB_DEFAULT_WIDTH;
461     gui.prev_wrap = -1;
462 
463 #if defined(ALWAYS_USE_GUI) || defined(VIMDLL)
464     result = OK;
465 #else
466 # ifdef FEAT_GUI_GTK
467     /*
468      * Note: Don't call gtk_init_check() before fork, it will be called after
469      * the fork. When calling it before fork, it make vim hang for a while.
470      * See gui_do_fork().
471      * Use a simpler check if the GUI window can probably be opened.
472      */
473     result = gui.dofork ? gui_mch_early_init_check(TRUE) : gui_mch_init_check();
474 # else
475     result = gui_mch_init_check();
476 # endif
477 #endif
478     return result;
479 }
480 
481 /*
482  * This is the call which starts the GUI.
483  */
484     void
485 gui_init(void)
486 {
487     win_T	*wp;
488     static int	recursive = 0;
489 
490     /*
491      * It's possible to use ":gui" in a .gvimrc file.  The first halve of this
492      * function will then be executed at the first call, the rest by the
493      * recursive call.  This allow the shell to be opened halfway reading a
494      * gvimrc file.
495      */
496     if (!recursive)
497     {
498 	++recursive;
499 
500 	clip_init(TRUE);
501 
502 	// If can't initialize, don't try doing the rest
503 	if (gui_init_check() == FAIL)
504 	{
505 	    --recursive;
506 	    clip_init(FALSE);
507 	    return;
508 	}
509 
510 	/*
511 	 * Reset 'paste'.  It's useful in the terminal, but not in the GUI.  It
512 	 * breaks the Paste toolbar button.
513 	 */
514 	set_option_value((char_u *)"paste", 0L, NULL, 0);
515 
516 	// Set t_Co to the number of colors: RGB.
517 	set_color_count(256 * 256 * 256);
518 
519 	/*
520 	 * Set up system-wide default menus.
521 	 */
522 #if defined(SYS_MENU_FILE) && defined(FEAT_MENU)
523 	if (vim_strchr(p_go, GO_NOSYSMENU) == NULL)
524 	{
525 	    sys_menu = TRUE;
526 	    do_source((char_u *)SYS_MENU_FILE, FALSE, DOSO_NONE, NULL);
527 	    sys_menu = FALSE;
528 	}
529 #endif
530 
531 	/*
532 	 * Switch on the mouse by default, unless the user changed it already.
533 	 * This can then be changed in the .gvimrc.
534 	 */
535 	if (!option_was_set((char_u *)"mouse"))
536 	    set_string_option_direct((char_u *)"mouse", -1,
537 					   (char_u *)"a", OPT_FREE, SID_NONE);
538 
539 	/*
540 	 * If -U option given, use only the initializations from that file and
541 	 * nothing else.  Skip all initializations for "-U NONE" or "-u NORC".
542 	 */
543 	if (use_gvimrc != NULL)
544 	{
545 	    if (STRCMP(use_gvimrc, "NONE") != 0
546 		    && STRCMP(use_gvimrc, "NORC") != 0
547 		    && do_source(use_gvimrc, FALSE, DOSO_NONE, NULL) != OK)
548 		semsg(_("E230: Cannot read from \"%s\""), use_gvimrc);
549 	}
550 	else
551 	{
552 	    /*
553 	     * Get system wide defaults for gvim, only when file name defined.
554 	     */
555 #ifdef SYS_GVIMRC_FILE
556 	    do_source((char_u *)SYS_GVIMRC_FILE, FALSE, DOSO_NONE, NULL);
557 #endif
558 
559 	    /*
560 	     * Try to read GUI initialization commands from the following
561 	     * places:
562 	     * - environment variable GVIMINIT
563 	     * - the user gvimrc file (~/.gvimrc)
564 	     * - the second user gvimrc file ($VIM/.gvimrc for Dos)
565 	     * - the third user gvimrc file ($VIM/.gvimrc for Amiga)
566 	     * The first that exists is used, the rest is ignored.
567 	     */
568 	    if (process_env((char_u *)"GVIMINIT", FALSE) == FAIL
569 		 && do_source((char_u *)USR_GVIMRC_FILE, TRUE,
570 						     DOSO_GVIMRC, NULL) == FAIL
571 #ifdef USR_GVIMRC_FILE2
572 		 && do_source((char_u *)USR_GVIMRC_FILE2, TRUE,
573 						     DOSO_GVIMRC, NULL) == FAIL
574 #endif
575 #ifdef USR_GVIMRC_FILE3
576 		 && do_source((char_u *)USR_GVIMRC_FILE3, TRUE,
577 						     DOSO_GVIMRC, NULL) == FAIL
578 #endif
579 				)
580 	    {
581 #ifdef USR_GVIMRC_FILE4
582 		(void)do_source((char_u *)USR_GVIMRC_FILE4, TRUE,
583 							    DOSO_GVIMRC, NULL);
584 #endif
585 	    }
586 
587 	    /*
588 	     * Read initialization commands from ".gvimrc" in current
589 	     * directory.  This is only done if the 'exrc' option is set.
590 	     * Because of security reasons we disallow shell and write
591 	     * commands now, except for unix if the file is owned by the user
592 	     * or 'secure' option has been reset in environment of global
593 	     * ".gvimrc".
594 	     * Only do this if GVIMRC_FILE is not the same as USR_GVIMRC_FILE,
595 	     * USR_GVIMRC_FILE2, USR_GVIMRC_FILE3 or SYS_GVIMRC_FILE.
596 	     */
597 	    if (p_exrc)
598 	    {
599 #ifdef UNIX
600 		{
601 		    stat_T s;
602 
603 		    // if ".gvimrc" file is not owned by user, set 'secure'
604 		    // mode
605 		    if (mch_stat(GVIMRC_FILE, &s) || s.st_uid != getuid())
606 			secure = p_secure;
607 		}
608 #else
609 		secure = p_secure;
610 #endif
611 
612 		if (       fullpathcmp((char_u *)USR_GVIMRC_FILE,
613 				(char_u *)GVIMRC_FILE, FALSE, TRUE) != FPC_SAME
614 #ifdef SYS_GVIMRC_FILE
615 			&& fullpathcmp((char_u *)SYS_GVIMRC_FILE,
616 				(char_u *)GVIMRC_FILE, FALSE, TRUE) != FPC_SAME
617 #endif
618 #ifdef USR_GVIMRC_FILE2
619 			&& fullpathcmp((char_u *)USR_GVIMRC_FILE2,
620 				(char_u *)GVIMRC_FILE, FALSE, TRUE) != FPC_SAME
621 #endif
622 #ifdef USR_GVIMRC_FILE3
623 			&& fullpathcmp((char_u *)USR_GVIMRC_FILE3,
624 				(char_u *)GVIMRC_FILE, FALSE, TRUE) != FPC_SAME
625 #endif
626 #ifdef USR_GVIMRC_FILE4
627 			&& fullpathcmp((char_u *)USR_GVIMRC_FILE4,
628 				(char_u *)GVIMRC_FILE, FALSE, TRUE) != FPC_SAME
629 #endif
630 			)
631 		    do_source((char_u *)GVIMRC_FILE, TRUE, DOSO_GVIMRC, NULL);
632 
633 		if (secure == 2)
634 		    need_wait_return = TRUE;
635 		secure = 0;
636 	    }
637 	}
638 
639 	if (need_wait_return || msg_didany)
640 	    wait_return(TRUE);
641 
642 	--recursive;
643     }
644 
645     // If recursive call opened the shell, return here from the first call
646     if (gui.in_use)
647 	return;
648 
649     /*
650      * Create the GUI shell.
651      */
652     gui.in_use = TRUE;		// Must be set after menus have been set up
653     if (gui_mch_init() == FAIL)
654 	goto error;
655 
656     // Avoid a delay for an error message that was printed in the terminal
657     // where Vim was started.
658     emsg_on_display = FALSE;
659     msg_scrolled = 0;
660     clear_sb_text(TRUE);
661     need_wait_return = FALSE;
662     msg_didany = FALSE;
663 
664     /*
665      * Check validity of any generic resources that may have been loaded.
666      */
667     if (gui.border_width < 0)
668 	gui.border_width = 0;
669 
670     /*
671      * Set up the fonts.  First use a font specified with "-fn" or "-font".
672      */
673     if (font_argument != NULL)
674 	set_option_value((char_u *)"gfn", 0L, (char_u *)font_argument, 0);
675     if (
676 #ifdef FEAT_XFONTSET
677 	    (*p_guifontset == NUL
678 	     || gui_init_font(p_guifontset, TRUE) == FAIL) &&
679 #endif
680 	    gui_init_font(*p_guifont == NUL ? hl_get_font_name()
681 						  : p_guifont, FALSE) == FAIL)
682     {
683 	emsg(_("E665: Cannot start GUI, no valid font found"));
684 	goto error2;
685     }
686     if (gui_get_wide_font() == FAIL)
687 	emsg(_("E231: 'guifontwide' invalid"));
688 
689     gui.num_cols = Columns;
690     gui.num_rows = Rows;
691     gui_reset_scroll_region();
692 
693     // Create initial scrollbars
694     FOR_ALL_WINDOWS(wp)
695     {
696 	gui_create_scrollbar(&wp->w_scrollbars[SBAR_LEFT], SBAR_LEFT, wp);
697 	gui_create_scrollbar(&wp->w_scrollbars[SBAR_RIGHT], SBAR_RIGHT, wp);
698     }
699     gui_create_scrollbar(&gui.bottom_sbar, SBAR_BOTTOM, NULL);
700 
701 #ifdef FEAT_MENU
702     gui_create_initial_menus(root_menu);
703 #endif
704 #ifdef FEAT_SIGN_ICONS
705     sign_gui_started();
706 #endif
707 
708     // Configure the desired menu and scrollbars
709     gui_init_which_components(NULL);
710 
711     // All components of the GUI have been created now
712     gui.shell_created = TRUE;
713 
714 #ifdef FEAT_GUI_MSWIN
715     // Set the shell size, adjusted for the screen size.  For GTK this only
716     // works after the shell has been opened, thus it is further down.
717     // If the window is already maximized (e.g. when --windowid is passed in),
718     // we want to use the system-provided dimensions by passing FALSE to
719     // mustset. Otherwise, we want to initialize with the default rows/columns.
720     if (gui_mch_maximized())
721 	gui_set_shellsize(FALSE, TRUE, RESIZE_BOTH);
722     else
723 	gui_set_shellsize(TRUE, TRUE, RESIZE_BOTH);
724 #else
725 # ifndef FEAT_GUI_GTK
726     gui_set_shellsize(FALSE, TRUE, RESIZE_BOTH);
727 # endif
728 #endif
729 #if defined(FEAT_GUI_MOTIF) && defined(FEAT_MENU)
730     // Need to set the size of the menubar after all the menus have been
731     // created.
732     gui_mch_compute_menu_height((Widget)0);
733 #endif
734 
735     /*
736      * Actually open the GUI shell.
737      */
738     if (gui_mch_open() != FAIL)
739     {
740 #ifdef FEAT_TITLE
741 	maketitle();
742 	resettitle();
743 #endif
744 	init_gui_options();
745 #ifdef FEAT_ARABIC
746 	// Our GUI can't do bidi.
747 	p_tbidi = FALSE;
748 #endif
749 #if defined(FEAT_GUI_GTK)
750 	// Give GTK+ a chance to put all widget's into place.
751 	gui_mch_update();
752 
753 # ifdef FEAT_MENU
754 	// If there is no 'm' in 'guioptions' we need to remove the menu now.
755 	// It was still there to make F10 work.
756 	if (vim_strchr(p_go, GO_MENUS) == NULL)
757 	{
758 	    --gui.starting;
759 	    gui_mch_enable_menu(FALSE);
760 	    ++gui.starting;
761 	    gui_mch_update();
762 	}
763 # endif
764 
765 	// Now make sure the shell fits on the screen.
766 	if (gui_mch_maximized())
767 	    gui_set_shellsize(FALSE, TRUE, RESIZE_BOTH);
768 	else
769 	    gui_set_shellsize(TRUE, TRUE, RESIZE_BOTH);
770 #endif
771 	// When 'lines' was set while starting up the topframe may have to be
772 	// resized.
773 	win_new_shellsize();
774 
775 #ifdef FEAT_BEVAL_GUI
776 	// Always create the Balloon Evaluation area, but disable it when
777 	// 'ballooneval' is off.
778 	if (balloonEval != NULL)
779 	{
780 # ifdef FEAT_VARTABS
781 	    vim_free(balloonEval->vts);
782 # endif
783 	    vim_free(balloonEval);
784 	}
785 	balloonEvalForTerm = FALSE;
786 # ifdef FEAT_GUI_GTK
787 	balloonEval = gui_mch_create_beval_area(gui.drawarea, NULL,
788 						     &general_beval_cb, NULL);
789 # else
790 #  if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)
791 	{
792 	    extern Widget	textArea;
793 	    balloonEval = gui_mch_create_beval_area(textArea, NULL,
794 						     &general_beval_cb, NULL);
795 	}
796 #  else
797 #   ifdef FEAT_GUI_MSWIN
798 	balloonEval = gui_mch_create_beval_area(NULL, NULL,
799 						     &general_beval_cb, NULL);
800 #   endif
801 #  endif
802 # endif
803 	if (!p_beval)
804 	    gui_mch_disable_beval_area(balloonEval);
805 #endif
806 
807 #ifndef FEAT_GUI_MSWIN
808 	// In the GUI modifiers are prepended to keys.
809 	// Don't do this for MS-Windows yet, it sends CTRL-K without the
810 	// modifier.
811 	seenModifyOtherKeys = TRUE;
812 #endif
813 
814 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
815 	if (!im_xim_isvalid_imactivate())
816 	    emsg(_("E599: Value of 'imactivatekey' is invalid"));
817 #endif
818 	// When 'cmdheight' was set during startup it may not have taken
819 	// effect yet.
820 	if (p_ch != 1L)
821 	    command_height();
822 
823 	return;
824     }
825 
826 error2:
827 #ifdef FEAT_GUI_X11
828     // undo gui_mch_init()
829     gui_mch_uninit();
830 #endif
831 
832 error:
833     gui.in_use = FALSE;
834     clip_init(FALSE);
835 }
836 
837 
838     void
839 gui_exit(int rc)
840 {
841     // don't free the fonts, it leads to a BUS error
842     // [email protected] Jul 99
843     free_highlight_fonts();
844     gui.in_use = FALSE;
845     gui_mch_exit(rc);
846 }
847 
848 #if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_X11) || defined(FEAT_GUI_MSWIN) \
849 	|| defined(FEAT_GUI_PHOTON) || defined(PROTO)
850 # define NEED_GUI_UPDATE_SCREEN 1
851 /*
852  * Called when the GUI shell is closed by the user.  If there are no changed
853  * files Vim exits, otherwise there will be a dialog to ask the user what to
854  * do.
855  * When this function returns, Vim should NOT exit!
856  */
857     void
858 gui_shell_closed(void)
859 {
860     cmdmod_T	    save_cmdmod = cmdmod;
861 
862     if (before_quit_autocmds(curwin, TRUE, FALSE))
863 	return;
864 
865     // Only exit when there are no changed files
866     exiting = TRUE;
867 # ifdef FEAT_BROWSE
868     cmdmod.cmod_flags |= CMOD_BROWSE;
869 # endif
870 # if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
871     cmdmod.cmod_flags |= CMOD_CONFIRM;
872 # endif
873     // If there are changed buffers, present the user with a dialog if
874     // possible, otherwise give an error message.
875     if (!check_changed_any(FALSE, FALSE))
876 	getout(0);
877 
878     exiting = FALSE;
879     cmdmod = save_cmdmod;
880     gui_update_screen();	// redraw, window may show changed buffer
881 }
882 #endif
883 
884 /*
885  * Set the font.  "font_list" is a comma separated list of font names.  The
886  * first font name that works is used.  If none is found, use the default
887  * font.
888  * If "fontset" is TRUE, the "font_list" is used as one name for the fontset.
889  * Return OK when able to set the font.  When it failed FAIL is returned and
890  * the fonts are unchanged.
891  */
892     int
893 gui_init_font(char_u *font_list, int fontset UNUSED)
894 {
895 #define FONTLEN 320
896     char_u	font_name[FONTLEN];
897     int		font_list_empty = FALSE;
898     int		ret = FAIL;
899 
900     if (!gui.in_use)
901 	return FAIL;
902 
903     font_name[0] = NUL;
904     if (*font_list == NUL)
905 	font_list_empty = TRUE;
906     else
907     {
908 #ifdef FEAT_XFONTSET
909 	// When using a fontset, the whole list of fonts is one name.
910 	if (fontset)
911 	    ret = gui_mch_init_font(font_list, TRUE);
912 	else
913 #endif
914 	    while (*font_list != NUL)
915 	    {
916 		// Isolate one comma separated font name.
917 		(void)copy_option_part(&font_list, font_name, FONTLEN, ",");
918 
919 		// Careful!!!  The Win32 version of gui_mch_init_font(), when
920 		// called with "*" will change p_guifont to the selected font
921 		// name, which frees the old value.  This makes font_list
922 		// invalid.  Thus when OK is returned here, font_list must no
923 		// longer be used!
924 		if (gui_mch_init_font(font_name, FALSE) == OK)
925 		{
926 #if !defined(FEAT_GUI_GTK)
927 		    // If it's a Unicode font, try setting 'guifontwide' to a
928 		    // similar double-width font.
929 		    if ((p_guifontwide == NULL || *p_guifontwide == NUL)
930 				&& strstr((char *)font_name, "10646") != NULL)
931 			set_guifontwide(font_name);
932 #endif
933 		    ret = OK;
934 		    break;
935 		}
936 	    }
937     }
938 
939     if (ret != OK
940 	    && STRCMP(font_list, "*") != 0
941 	    && (font_list_empty || gui.norm_font == NOFONT))
942     {
943 	/*
944 	 * Couldn't load any font in 'font_list', keep the current font if
945 	 * there is one.  If 'font_list' is empty, or if there is no current
946 	 * font, tell gui_mch_init_font() to try to find a font we can load.
947 	 */
948 	ret = gui_mch_init_font(NULL, FALSE);
949     }
950 
951     if (ret == OK)
952     {
953 #ifndef FEAT_GUI_GTK
954 	// Set normal font as current font
955 # ifdef FEAT_XFONTSET
956 	if (gui.fontset != NOFONTSET)
957 	    gui_mch_set_fontset(gui.fontset);
958 	else
959 # endif
960 	    gui_mch_set_font(gui.norm_font);
961 #endif
962 	gui_set_shellsize(FALSE, TRUE, RESIZE_BOTH);
963     }
964 
965     return ret;
966 }
967 
968 #ifndef FEAT_GUI_GTK
969 /*
970  * Try setting 'guifontwide' to a font twice as wide as "name".
971  */
972     static void
973 set_guifontwide(char_u *name)
974 {
975     int		i = 0;
976     char_u	wide_name[FONTLEN + 10]; // room for 2 * width and '*'
977     char_u	*wp = NULL;
978     char_u	*p;
979     GuiFont	font;
980 
981     wp = wide_name;
982     for (p = name; *p != NUL; ++p)
983     {
984 	*wp++ = *p;
985 	if (*p == '-')
986 	{
987 	    ++i;
988 	    if (i == 6)		// font type: change "--" to "-*-"
989 	    {
990 		if (p[1] == '-')
991 		    *wp++ = '*';
992 	    }
993 	    else if (i == 12)	// found the width
994 	    {
995 		++p;
996 		i = getdigits(&p);
997 		if (i != 0)
998 		{
999 		    // Double the width specification.
1000 		    sprintf((char *)wp, "%d%s", i * 2, p);
1001 		    font = gui_mch_get_font(wide_name, FALSE);
1002 		    if (font != NOFONT)
1003 		    {
1004 			gui_mch_free_font(gui.wide_font);
1005 			gui.wide_font = font;
1006 			set_string_option_direct((char_u *)"gfw", -1,
1007 						      wide_name, OPT_FREE, 0);
1008 		    }
1009 		}
1010 		break;
1011 	    }
1012 	}
1013     }
1014 }
1015 #endif // !FEAT_GUI_GTK
1016 
1017 /*
1018  * Get the font for 'guifontwide'.
1019  * Return FAIL for an invalid font name.
1020  */
1021     int
1022 gui_get_wide_font(void)
1023 {
1024     GuiFont	font = NOFONT;
1025     char_u	font_name[FONTLEN];
1026     char_u	*p;
1027 
1028     if (!gui.in_use)	    // Can't allocate font yet, assume it's OK.
1029 	return OK;	    // Will give an error message later.
1030 
1031     if (p_guifontwide != NULL && *p_guifontwide != NUL)
1032     {
1033 	for (p = p_guifontwide; *p != NUL; )
1034 	{
1035 	    // Isolate one comma separated font name.
1036 	    (void)copy_option_part(&p, font_name, FONTLEN, ",");
1037 	    font = gui_mch_get_font(font_name, FALSE);
1038 	    if (font != NOFONT)
1039 		break;
1040 	}
1041 	if (font == NOFONT)
1042 	    return FAIL;
1043     }
1044 
1045     gui_mch_free_font(gui.wide_font);
1046 #ifdef FEAT_GUI_GTK
1047     // Avoid unnecessary overhead if 'guifontwide' is equal to 'guifont'.
1048     if (font != NOFONT && gui.norm_font != NOFONT
1049 			 && pango_font_description_equal(font, gui.norm_font))
1050     {
1051 	gui.wide_font = NOFONT;
1052 	gui_mch_free_font(font);
1053     }
1054     else
1055 #endif
1056 	gui.wide_font = font;
1057 #ifdef FEAT_GUI_MSWIN
1058     gui_mch_wide_font_changed();
1059 #else
1060     /*
1061      * TODO: setup wide_bold_font, wide_ital_font and wide_boldital_font to
1062      * support those fonts for 'guifontwide'.
1063      */
1064 #endif
1065     return OK;
1066 }
1067 
1068     static void
1069 gui_set_cursor(int row, int col)
1070 {
1071     gui.row = row;
1072     gui.col = col;
1073 }
1074 
1075 /*
1076  * gui_check_pos - check if the cursor is on the screen.
1077  */
1078     static void
1079 gui_check_pos(void)
1080 {
1081     if (gui.row >= screen_Rows)
1082 	gui.row = screen_Rows - 1;
1083     if (gui.col >= screen_Columns)
1084 	gui.col = screen_Columns - 1;
1085     if (gui.cursor_row >= screen_Rows || gui.cursor_col >= screen_Columns)
1086 	gui.cursor_is_valid = FALSE;
1087 }
1088 
1089 /*
1090  * Redraw the cursor if necessary or when forced.
1091  * Careful: The contents of ScreenLines[] must match what is on the screen,
1092  * otherwise this goes wrong.  May need to call out_flush() first.
1093  */
1094     void
1095 gui_update_cursor(
1096     int		force,		 // when TRUE, update even when not moved
1097     int		clear_selection) // clear selection under cursor
1098 {
1099     int		cur_width = 0;
1100     int		cur_height = 0;
1101     int		old_hl_mask;
1102     cursorentry_T *shape;
1103     int		id;
1104 #ifdef FEAT_TERMINAL
1105     guicolor_T	shape_fg = INVALCOLOR;
1106     guicolor_T	shape_bg = INVALCOLOR;
1107 #endif
1108     guicolor_T	cfg, cbg, cc;	// cursor fore-/background color
1109     int		cattr;		// cursor attributes
1110     int		attr;
1111     attrentry_T *aep = NULL;
1112 
1113     // Don't update the cursor when halfway busy scrolling or the screen size
1114     // doesn't match 'columns' and 'lines.  ScreenLines[] isn't valid then.
1115     if (!can_update_cursor || screen_Columns != gui.num_cols
1116 					       || screen_Rows != gui.num_rows)
1117 	return;
1118 
1119     gui_check_pos();
1120     if (!gui.cursor_is_valid || force
1121 		    || gui.row != gui.cursor_row || gui.col != gui.cursor_col)
1122     {
1123 	gui_undraw_cursor();
1124 
1125 	// If a cursor-less sleep is ongoing, leave the cursor invisible
1126 	if (cursor_is_sleeping())
1127 	    return;
1128 
1129 	if (gui.row < 0)
1130 	    return;
1131 #ifdef HAVE_INPUT_METHOD
1132 	if (gui.row != gui.cursor_row || gui.col != gui.cursor_col)
1133 	    im_set_position(gui.row, gui.col);
1134 #endif
1135 	gui.cursor_row = gui.row;
1136 	gui.cursor_col = gui.col;
1137 
1138 	// Only write to the screen after ScreenLines[] has been initialized
1139 	if (!screen_cleared || ScreenLines == NULL)
1140 	    return;
1141 
1142 	// Clear the selection if we are about to write over it
1143 	if (clear_selection)
1144 	    clip_may_clear_selection(gui.row, gui.row);
1145 	// Check that the cursor is inside the shell (resizing may have made
1146 	// it invalid)
1147 	if (gui.row >= screen_Rows || gui.col >= screen_Columns)
1148 	    return;
1149 
1150 	gui.cursor_is_valid = TRUE;
1151 
1152 	/*
1153 	 * How the cursor is drawn depends on the current mode.
1154 	 * When in a terminal window use the shape/color specified there.
1155 	 */
1156 #ifdef FEAT_TERMINAL
1157 	if (terminal_is_active())
1158 	    shape = term_get_cursor_shape(&shape_fg, &shape_bg);
1159 	else
1160 #endif
1161 	    shape = &shape_table[get_shape_idx(FALSE)];
1162 	if (State & LANGMAP)
1163 	    id = shape->id_lm;
1164 	else
1165 	    id = shape->id;
1166 
1167 	// get the colors and attributes for the cursor.  Default is inverted
1168 	cfg = INVALCOLOR;
1169 	cbg = INVALCOLOR;
1170 	cattr = HL_INVERSE;
1171 	gui_mch_set_blinking(shape->blinkwait,
1172 			     shape->blinkon,
1173 			     shape->blinkoff);
1174 	if (shape->blinkwait == 0 || shape->blinkon == 0
1175 						       || shape->blinkoff == 0)
1176 	    gui_mch_stop_blink(FALSE);
1177 #ifdef FEAT_TERMINAL
1178 	if (shape_bg != INVALCOLOR)
1179 	{
1180 	    cattr = 0;
1181 	    cfg = shape_fg;
1182 	    cbg = shape_bg;
1183 	}
1184 	else
1185 #endif
1186 	if (id > 0)
1187 	{
1188 	    cattr = syn_id2colors(id, &cfg, &cbg);
1189 #if defined(HAVE_INPUT_METHOD)
1190 	    {
1191 		static int iid;
1192 		guicolor_T fg, bg;
1193 
1194 		if (
1195 # if defined(FEAT_GUI_GTK) && defined(FEAT_XIM)
1196 			preedit_get_status()
1197 # else
1198 			im_get_status()
1199 # endif
1200 			)
1201 		{
1202 		    iid = syn_name2id((char_u *)"CursorIM");
1203 		    if (iid > 0)
1204 		    {
1205 			syn_id2colors(iid, &fg, &bg);
1206 			if (bg != INVALCOLOR)
1207 			    cbg = bg;
1208 			if (fg != INVALCOLOR)
1209 			    cfg = fg;
1210 		    }
1211 		}
1212 	    }
1213 #endif
1214 	}
1215 
1216 	/*
1217 	 * Get the attributes for the character under the cursor.
1218 	 * When no cursor color was given, use the character color.
1219 	 */
1220 	attr = ScreenAttrs[LineOffset[gui.row] + gui.col];
1221 	if (attr > HL_ALL)
1222 	    aep = syn_gui_attr2entry(attr);
1223 	if (aep != NULL)
1224 	{
1225 	    attr = aep->ae_attr;
1226 	    if (cfg == INVALCOLOR)
1227 		cfg = ((attr & HL_INVERSE)  ? aep->ae_u.gui.bg_color
1228 					    : aep->ae_u.gui.fg_color);
1229 	    if (cbg == INVALCOLOR)
1230 		cbg = ((attr & HL_INVERSE)  ? aep->ae_u.gui.fg_color
1231 					    : aep->ae_u.gui.bg_color);
1232 	}
1233 	if (cfg == INVALCOLOR)
1234 	    cfg = (attr & HL_INVERSE) ? gui.back_pixel : gui.norm_pixel;
1235 	if (cbg == INVALCOLOR)
1236 	    cbg = (attr & HL_INVERSE) ? gui.norm_pixel : gui.back_pixel;
1237 
1238 #ifdef FEAT_XIM
1239 	if (aep != NULL)
1240 	{
1241 	    xim_bg_color = ((attr & HL_INVERSE) ? aep->ae_u.gui.fg_color
1242 						: aep->ae_u.gui.bg_color);
1243 	    xim_fg_color = ((attr & HL_INVERSE) ? aep->ae_u.gui.bg_color
1244 						: aep->ae_u.gui.fg_color);
1245 	    if (xim_bg_color == INVALCOLOR)
1246 		xim_bg_color = (attr & HL_INVERSE) ? gui.norm_pixel
1247 						   : gui.back_pixel;
1248 	    if (xim_fg_color == INVALCOLOR)
1249 		xim_fg_color = (attr & HL_INVERSE) ? gui.back_pixel
1250 						   : gui.norm_pixel;
1251 	}
1252 	else
1253 	{
1254 	    xim_bg_color = (attr & HL_INVERSE) ? gui.norm_pixel
1255 					       : gui.back_pixel;
1256 	    xim_fg_color = (attr & HL_INVERSE) ? gui.back_pixel
1257 					       : gui.norm_pixel;
1258 	}
1259 #endif
1260 
1261 	attr &= ~HL_INVERSE;
1262 	if (cattr & HL_INVERSE)
1263 	{
1264 	    cc = cbg;
1265 	    cbg = cfg;
1266 	    cfg = cc;
1267 	}
1268 	cattr &= ~HL_INVERSE;
1269 
1270 	/*
1271 	 * When we don't have window focus, draw a hollow cursor.
1272 	 */
1273 	if (!gui.in_focus)
1274 	{
1275 	    gui_mch_draw_hollow_cursor(cbg);
1276 	    return;
1277 	}
1278 
1279 	old_hl_mask = gui.highlight_mask;
1280 	if (shape->shape == SHAPE_BLOCK)
1281 	{
1282 	    /*
1283 	     * Draw the text character with the cursor colors.	Use the
1284 	     * character attributes plus the cursor attributes.
1285 	     */
1286 	    gui.highlight_mask = (cattr | attr);
1287 	    (void)gui_screenchar(LineOffset[gui.row] + gui.col,
1288 			GUI_MON_IS_CURSOR | GUI_MON_NOCLEAR, cfg, cbg, 0);
1289 	}
1290 	else
1291 	{
1292 #if defined(FEAT_RIGHTLEFT)
1293 	    int	    col_off = FALSE;
1294 #endif
1295 	    /*
1296 	     * First draw the partial cursor, then overwrite with the text
1297 	     * character, using a transparent background.
1298 	     */
1299 	    if (shape->shape == SHAPE_VER)
1300 	    {
1301 		cur_height = gui.char_height;
1302 		cur_width = (gui.char_width * shape->percentage + 99) / 100;
1303 	    }
1304 	    else
1305 	    {
1306 		cur_height = (gui.char_height * shape->percentage + 99) / 100;
1307 		cur_width = gui.char_width;
1308 	    }
1309 	    if (has_mbyte && (*mb_off2cells)(LineOffset[gui.row] + gui.col,
1310 				    LineOffset[gui.row] + screen_Columns) > 1)
1311 	    {
1312 		// Double wide character.
1313 		if (shape->shape != SHAPE_VER)
1314 		    cur_width += gui.char_width;
1315 #ifdef FEAT_RIGHTLEFT
1316 		if (CURSOR_BAR_RIGHT)
1317 		{
1318 		    // gui.col points to the left halve of the character but
1319 		    // the vertical line needs to be on the right halve.
1320 		    // A double-wide horizontal line is also drawn from the
1321 		    // right halve in gui_mch_draw_part_cursor().
1322 		    col_off = TRUE;
1323 		    ++gui.col;
1324 		}
1325 #endif
1326 	    }
1327 	    gui_mch_draw_part_cursor(cur_width, cur_height, cbg);
1328 #if defined(FEAT_RIGHTLEFT)
1329 	    if (col_off)
1330 		--gui.col;
1331 #endif
1332 
1333 #ifndef FEAT_GUI_MSWIN	    // doesn't seem to work for MSWindows
1334 	    gui.highlight_mask = ScreenAttrs[LineOffset[gui.row] + gui.col];
1335 	    (void)gui_screenchar(LineOffset[gui.row] + gui.col,
1336 		    GUI_MON_TRS_CURSOR | GUI_MON_NOCLEAR,
1337 		    (guicolor_T)0, (guicolor_T)0, 0);
1338 #endif
1339 	}
1340 	gui.highlight_mask = old_hl_mask;
1341     }
1342 }
1343 
1344 #if defined(FEAT_MENU) || defined(PROTO)
1345     void
1346 gui_position_menu(void)
1347 {
1348 # if !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_MOTIF)
1349     if (gui.menu_is_active && gui.in_use)
1350 	gui_mch_set_menu_pos(0, 0, gui.menu_width, gui.menu_height);
1351 # endif
1352 }
1353 #endif
1354 
1355 /*
1356  * Position the various GUI components (text area, menu).  The vertical
1357  * scrollbars are NOT handled here.  See gui_update_scrollbars().
1358  */
1359     static void
1360 gui_position_components(int total_width UNUSED)
1361 {
1362     int	    text_area_x;
1363     int	    text_area_y;
1364     int	    text_area_width;
1365     int	    text_area_height;
1366 
1367     // avoid that moving components around generates events
1368     ++hold_gui_events;
1369 
1370     text_area_x = 0;
1371     if (gui.which_scrollbars[SBAR_LEFT])
1372 	text_area_x += gui.scrollbar_width;
1373 
1374     text_area_y = 0;
1375 #if defined(FEAT_MENU) && !(defined(FEAT_GUI_GTK) || defined(FEAT_GUI_PHOTON))
1376     gui.menu_width = total_width;
1377     if (gui.menu_is_active)
1378 	text_area_y += gui.menu_height;
1379 #endif
1380 #if defined(FEAT_TOOLBAR) && defined(FEAT_GUI_MSWIN)
1381     if (vim_strchr(p_go, GO_TOOLBAR) != NULL)
1382 	text_area_y = TOOLBAR_BUTTON_HEIGHT + TOOLBAR_BORDER_HEIGHT;
1383 #endif
1384 
1385 # if defined(FEAT_GUI_TABLINE) && (defined(FEAT_GUI_MSWIN) \
1386 	|| defined(FEAT_GUI_MOTIF))
1387     if (gui_has_tabline())
1388 	text_area_y += gui.tabline_height;
1389 #endif
1390 
1391 #if defined(FEAT_TOOLBAR) && (defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA) \
1392 	|| defined(FEAT_GUI_HAIKU))
1393     if (vim_strchr(p_go, GO_TOOLBAR) != NULL)
1394     {
1395 # if defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_HAIKU)
1396 	gui_mch_set_toolbar_pos(0, text_area_y,
1397 				gui.menu_width, gui.toolbar_height);
1398 # endif
1399 	text_area_y += gui.toolbar_height;
1400     }
1401 #endif
1402 
1403 # if defined(FEAT_GUI_TABLINE) && defined(FEAT_GUI_HAIKU)
1404     gui_mch_set_tabline_pos(0, text_area_y,
1405     gui.menu_width, gui.tabline_height);
1406     if (gui_has_tabline())
1407 	text_area_y += gui.tabline_height;
1408 #endif
1409 
1410     text_area_width = gui.num_cols * gui.char_width + gui.border_offset * 2;
1411     text_area_height = gui.num_rows * gui.char_height + gui.border_offset * 2;
1412 
1413     gui_mch_set_text_area_pos(text_area_x,
1414 			      text_area_y,
1415 			      text_area_width,
1416 			      text_area_height
1417 #if defined(FEAT_XIM) && !defined(FEAT_GUI_GTK)
1418 				  + xim_get_status_area_height()
1419 #endif
1420 			      );
1421 #ifdef FEAT_MENU
1422     gui_position_menu();
1423 #endif
1424     if (gui.which_scrollbars[SBAR_BOTTOM])
1425 	gui_mch_set_scrollbar_pos(&gui.bottom_sbar,
1426 				  text_area_x,
1427 				  text_area_y + text_area_height
1428 					+ gui_mch_get_scrollbar_ypadding(),
1429 				  text_area_width,
1430 				  gui.scrollbar_height);
1431     gui.left_sbar_x = 0;
1432     gui.right_sbar_x = text_area_x + text_area_width
1433 					+ gui_mch_get_scrollbar_xpadding();
1434 
1435     --hold_gui_events;
1436 }
1437 
1438 /*
1439  * Get the width of the widgets and decorations to the side of the text area.
1440  */
1441     int
1442 gui_get_base_width(void)
1443 {
1444     int	    base_width;
1445 
1446     base_width = 2 * gui.border_offset;
1447     if (gui.which_scrollbars[SBAR_LEFT])
1448 	base_width += gui.scrollbar_width;
1449     if (gui.which_scrollbars[SBAR_RIGHT])
1450 	base_width += gui.scrollbar_width;
1451     return base_width;
1452 }
1453 
1454 /*
1455  * Get the height of the widgets and decorations above and below the text area.
1456  */
1457     int
1458 gui_get_base_height(void)
1459 {
1460     int	    base_height;
1461 
1462     base_height = 2 * gui.border_offset;
1463     if (gui.which_scrollbars[SBAR_BOTTOM])
1464 	base_height += gui.scrollbar_height;
1465 #ifdef FEAT_GUI_GTK
1466     // We can't take the sizes properly into account until anything is
1467     // realized.  Therefore we recalculate all the values here just before
1468     // setting the size. (--mdcki)
1469 #else
1470 # ifdef FEAT_MENU
1471     if (gui.menu_is_active)
1472 	base_height += gui.menu_height;
1473 # endif
1474 # ifdef FEAT_TOOLBAR
1475     if (vim_strchr(p_go, GO_TOOLBAR) != NULL)
1476 #  if defined(FEAT_GUI_MSWIN) && defined(FEAT_TOOLBAR)
1477 	base_height += (TOOLBAR_BUTTON_HEIGHT + TOOLBAR_BORDER_HEIGHT);
1478 #  else
1479 	base_height += gui.toolbar_height;
1480 #  endif
1481 # endif
1482 # if defined(FEAT_GUI_TABLINE) && (defined(FEAT_GUI_MSWIN) \
1483 	|| defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_HAIKU))
1484     if (gui_has_tabline())
1485 	base_height += gui.tabline_height;
1486 # endif
1487 # ifdef FEAT_FOOTER
1488     if (vim_strchr(p_go, GO_FOOTER) != NULL)
1489 	base_height += gui.footer_height;
1490 # endif
1491 # if defined(FEAT_GUI_MOTIF) && defined(FEAT_MENU)
1492     base_height += gui_mch_text_area_extra_height();
1493 # endif
1494 #endif
1495     return base_height;
1496 }
1497 
1498 /*
1499  * Should be called after the GUI shell has been resized.  Its arguments are
1500  * the new width and height of the shell in pixels.
1501  */
1502     void
1503 gui_resize_shell(int pixel_width, int pixel_height)
1504 {
1505     static int	busy = FALSE;
1506 
1507     if (!gui.shell_created)	    // ignore when still initializing
1508 	return;
1509 
1510     /*
1511      * Can't resize the screen while it is being redrawn.  Remember the new
1512      * size and handle it later.
1513      */
1514     if (updating_screen || busy)
1515     {
1516 	new_pixel_width = pixel_width;
1517 	new_pixel_height = pixel_height;
1518 	return;
1519     }
1520 
1521 again:
1522     new_pixel_width = 0;
1523     new_pixel_height = 0;
1524     busy = TRUE;
1525 
1526 #ifdef FEAT_GUI_HAIKU
1527     vim_lock_screen();
1528 #endif
1529 
1530     // Flush pending output before redrawing
1531     out_flush();
1532 
1533     gui.num_cols = (pixel_width - gui_get_base_width()) / gui.char_width;
1534     gui.num_rows = (pixel_height - gui_get_base_height()) / gui.char_height;
1535 
1536     gui_position_components(pixel_width);
1537     gui_reset_scroll_region();
1538 
1539     /*
1540      * At the "more" and ":confirm" prompt there is no redraw, put the cursor
1541      * at the last line here (why does it have to be one row too low?).
1542      */
1543     if (State == ASKMORE || State == CONFIRM)
1544 	gui.row = gui.num_rows;
1545 
1546     // Only comparing Rows and Columns may be sufficient, but let's stay on
1547     // the safe side.
1548     if (gui.num_rows != screen_Rows || gui.num_cols != screen_Columns
1549 	    || gui.num_rows != Rows || gui.num_cols != Columns)
1550 	shell_resized();
1551 
1552 #ifdef FEAT_GUI_HAIKU
1553     vim_unlock_screen();
1554 #endif
1555 
1556     gui_update_scrollbars(TRUE);
1557     gui_update_cursor(FALSE, TRUE);
1558 #if defined(FEAT_XIM) && !defined(FEAT_GUI_GTK)
1559     xim_set_status_area();
1560 #endif
1561 
1562     busy = FALSE;
1563 
1564     // We may have been called again while redrawing the screen.
1565     // Need to do it all again with the latest size then.  But only if the size
1566     // actually changed.
1567     if (new_pixel_height)
1568     {
1569 	if (pixel_width == new_pixel_width && pixel_height == new_pixel_height)
1570 	{
1571 	    new_pixel_width = 0;
1572 	    new_pixel_height = 0;
1573 	}
1574 	else
1575 	{
1576 	    pixel_width = new_pixel_width;
1577 	    pixel_height = new_pixel_height;
1578 	    goto again;
1579 	}
1580     }
1581 }
1582 
1583 /*
1584  * Check if gui_resize_shell() must be called.
1585  */
1586     void
1587 gui_may_resize_shell(void)
1588 {
1589     if (new_pixel_height)
1590 	// careful: gui_resize_shell() may postpone the resize again if we
1591 	// were called indirectly by it
1592 	gui_resize_shell(new_pixel_width, new_pixel_height);
1593 }
1594 
1595     int
1596 gui_get_shellsize(void)
1597 {
1598     Rows = gui.num_rows;
1599     Columns = gui.num_cols;
1600     return OK;
1601 }
1602 
1603 /*
1604  * Set the size of the Vim shell according to Rows and Columns.
1605  * If "fit_to_display" is TRUE then the size may be reduced to fit the window
1606  * on the screen.
1607  * When "mustset" is TRUE the size was set by the user. When FALSE a UI
1608  * component was added or removed (e.g., a scrollbar).
1609  */
1610     void
1611 gui_set_shellsize(
1612     int		mustset UNUSED,
1613     int		fit_to_display,
1614     int		direction)		// RESIZE_HOR, RESIZE_VER
1615 {
1616     int		base_width;
1617     int		base_height;
1618     int		width;
1619     int		height;
1620     int		min_width;
1621     int		min_height;
1622     int		screen_w;
1623     int		screen_h;
1624 #ifdef FEAT_GUI_GTK
1625     int		un_maximize = mustset;
1626     int		did_adjust = 0;
1627 #endif
1628     int		x = -1, y = -1;
1629 
1630     if (!gui.shell_created)
1631 	return;
1632 
1633 #if defined(MSWIN) || defined(FEAT_GUI_GTK)
1634     // If not setting to a user specified size and maximized, calculate the
1635     // number of characters that fit in the maximized window.
1636     if (!mustset && (vim_strchr(p_go, GO_KEEPWINSIZE) != NULL
1637 						       || gui_mch_maximized()))
1638     {
1639 	gui_mch_newfont();
1640 	return;
1641     }
1642 #endif
1643 
1644     base_width = gui_get_base_width();
1645     base_height = gui_get_base_height();
1646     if (fit_to_display)
1647 	// Remember the original window position.
1648 	(void)gui_mch_get_winpos(&x, &y);
1649 
1650     width = Columns * gui.char_width + base_width;
1651     height = Rows * gui.char_height + base_height;
1652 
1653     if (fit_to_display)
1654     {
1655 	gui_mch_get_screen_dimensions(&screen_w, &screen_h);
1656 	if ((direction & RESIZE_HOR) && width > screen_w)
1657 	{
1658 	    Columns = (screen_w - base_width) / gui.char_width;
1659 	    if (Columns < MIN_COLUMNS)
1660 		Columns = MIN_COLUMNS;
1661 	    width = Columns * gui.char_width + base_width;
1662 #ifdef FEAT_GUI_GTK
1663 	    ++did_adjust;
1664 #endif
1665 	}
1666 	if ((direction & RESIZE_VERT) && height > screen_h)
1667 	{
1668 	    Rows = (screen_h - base_height) / gui.char_height;
1669 	    check_shellsize();
1670 	    height = Rows * gui.char_height + base_height;
1671 #ifdef FEAT_GUI_GTK
1672 	    ++did_adjust;
1673 #endif
1674 	}
1675 #ifdef FEAT_GUI_GTK
1676 	if (did_adjust == 2 || (width + gui.char_width >= screen_w
1677 				     && height + gui.char_height >= screen_h))
1678 	    // don't unmaximize if at maximum size
1679 	    un_maximize = FALSE;
1680 #endif
1681     }
1682     limit_screen_size();
1683     gui.num_cols = Columns;
1684     gui.num_rows = Rows;
1685 
1686     min_width = base_width + MIN_COLUMNS * gui.char_width;
1687     min_height = base_height + MIN_LINES * gui.char_height;
1688     min_height += tabline_height() * gui.char_height;
1689 
1690 #ifdef FEAT_GUI_GTK
1691     if (un_maximize)
1692     {
1693 	// If the window size is smaller than the screen unmaximize the
1694 	// window, otherwise resizing won't work.
1695 	gui_mch_get_screen_dimensions(&screen_w, &screen_h);
1696 	if ((width + gui.char_width < screen_w
1697 				   || height + gui.char_height * 2 < screen_h)
1698 		&& gui_mch_maximized())
1699 	    gui_mch_unmaximize();
1700     }
1701 #endif
1702 
1703     gui_mch_set_shellsize(width, height, min_width, min_height,
1704 					  base_width, base_height, direction);
1705 
1706     if (fit_to_display && x >= 0 && y >= 0)
1707     {
1708 	// Some window managers put the Vim window left of/above the screen.
1709 	// Only change the position if it wasn't already negative before
1710 	// (happens on MS-Windows with a secondary monitor).
1711 	gui_mch_update();
1712 	if (gui_mch_get_winpos(&x, &y) == OK && (x < 0 || y < 0))
1713 	    gui_mch_set_winpos(x < 0 ? 0 : x, y < 0 ? 0 : y);
1714     }
1715 
1716     gui_position_components(width);
1717     gui_update_scrollbars(TRUE);
1718     gui_reset_scroll_region();
1719 }
1720 
1721 /*
1722  * Called when Rows and/or Columns has changed.
1723  */
1724     void
1725 gui_new_shellsize(void)
1726 {
1727     gui_reset_scroll_region();
1728 }
1729 
1730 /*
1731  * Make scroll region cover whole screen.
1732  */
1733     static void
1734 gui_reset_scroll_region(void)
1735 {
1736     gui.scroll_region_top = 0;
1737     gui.scroll_region_bot = gui.num_rows - 1;
1738     gui.scroll_region_left = 0;
1739     gui.scroll_region_right = gui.num_cols - 1;
1740 }
1741 
1742     static void
1743 gui_start_highlight(int mask)
1744 {
1745     if (mask > HL_ALL)		    // highlight code
1746 	gui.highlight_mask = mask;
1747     else			    // mask
1748 	gui.highlight_mask |= mask;
1749 }
1750 
1751     void
1752 gui_stop_highlight(int mask)
1753 {
1754     if (mask > HL_ALL)		    // highlight code
1755 	gui.highlight_mask = HL_NORMAL;
1756     else			    // mask
1757 	gui.highlight_mask &= ~mask;
1758 }
1759 
1760 /*
1761  * Clear a rectangular region of the screen from text pos (row1, col1) to
1762  * (row2, col2) inclusive.
1763  */
1764     void
1765 gui_clear_block(
1766     int	    row1,
1767     int	    col1,
1768     int	    row2,
1769     int	    col2)
1770 {
1771     // Clear the selection if we are about to write over it
1772     clip_may_clear_selection(row1, row2);
1773 
1774     gui_mch_clear_block(row1, col1, row2, col2);
1775 
1776     // Invalidate cursor if it was in this block
1777     if (       gui.cursor_row >= row1 && gui.cursor_row <= row2
1778 	    && gui.cursor_col >= col1 && gui.cursor_col <= col2)
1779 	gui.cursor_is_valid = FALSE;
1780 }
1781 
1782 /*
1783  * Write code to update the cursor later.  This avoids the need to flush the
1784  * output buffer before calling gui_update_cursor().
1785  */
1786     void
1787 gui_update_cursor_later(void)
1788 {
1789     OUT_STR(IF_EB("\033|s", ESC_STR "|s"));
1790 }
1791 
1792     void
1793 gui_write(
1794     char_u	*s,
1795     int		len)
1796 {
1797     char_u	*p;
1798     int		arg1 = 0, arg2 = 0;
1799     int		force_cursor = FALSE;	// force cursor update
1800     int		force_scrollbar = FALSE;
1801     static win_T	*old_curwin = NULL;
1802 
1803 // #define DEBUG_GUI_WRITE
1804 #ifdef DEBUG_GUI_WRITE
1805     {
1806 	int i;
1807 	char_u *str;
1808 
1809 	printf("gui_write(%d):\n    ", len);
1810 	for (i = 0; i < len; i++)
1811 	    if (s[i] == ESC)
1812 	    {
1813 		if (i != 0)
1814 		    printf("\n    ");
1815 		printf("<ESC>");
1816 	    }
1817 	    else
1818 	    {
1819 		str = transchar_byte(s[i]);
1820 		if (str[0] && str[1])
1821 		    printf("<%s>", (char *)str);
1822 		else
1823 		    printf("%s", (char *)str);
1824 	    }
1825 	printf("\n");
1826     }
1827 #endif
1828     while (len)
1829     {
1830 	if (s[0] == ESC && s[1] == '|')
1831 	{
1832 	    p = s + 2;
1833 	    if (VIM_ISDIGIT(*p) || (*p == '-' && VIM_ISDIGIT(*(p + 1))))
1834 	    {
1835 		arg1 = getdigits(&p);
1836 		if (p > s + len)
1837 		    break;
1838 		if (*p == ';')
1839 		{
1840 		    ++p;
1841 		    arg2 = getdigits(&p);
1842 		    if (p > s + len)
1843 			break;
1844 		}
1845 	    }
1846 	    switch (*p)
1847 	    {
1848 		case 'C':	// Clear screen
1849 		    clip_scroll_selection(9999);
1850 		    gui_mch_clear_all();
1851 		    gui.cursor_is_valid = FALSE;
1852 		    force_scrollbar = TRUE;
1853 		    break;
1854 		case 'M':	// Move cursor
1855 		    gui_set_cursor(arg1, arg2);
1856 		    break;
1857 		case 's':	// force cursor (shape) update
1858 		    force_cursor = TRUE;
1859 		    break;
1860 		case 'R':	// Set scroll region
1861 		    if (arg1 < arg2)
1862 		    {
1863 			gui.scroll_region_top = arg1;
1864 			gui.scroll_region_bot = arg2;
1865 		    }
1866 		    else
1867 		    {
1868 			gui.scroll_region_top = arg2;
1869 			gui.scroll_region_bot = arg1;
1870 		    }
1871 		    break;
1872 		case 'V':	// Set vertical scroll region
1873 		    if (arg1 < arg2)
1874 		    {
1875 			gui.scroll_region_left = arg1;
1876 			gui.scroll_region_right = arg2;
1877 		    }
1878 		    else
1879 		    {
1880 			gui.scroll_region_left = arg2;
1881 			gui.scroll_region_right = arg1;
1882 		    }
1883 		    break;
1884 		case 'd':	// Delete line
1885 		    gui_delete_lines(gui.row, 1);
1886 		    break;
1887 		case 'D':	// Delete lines
1888 		    gui_delete_lines(gui.row, arg1);
1889 		    break;
1890 		case 'i':	// Insert line
1891 		    gui_insert_lines(gui.row, 1);
1892 		    break;
1893 		case 'I':	// Insert lines
1894 		    gui_insert_lines(gui.row, arg1);
1895 		    break;
1896 		case '$':	// Clear to end-of-line
1897 		    gui_clear_block(gui.row, gui.col, gui.row,
1898 							    (int)Columns - 1);
1899 		    break;
1900 		case 'h':	// Turn on highlighting
1901 		    gui_start_highlight(arg1);
1902 		    break;
1903 		case 'H':	// Turn off highlighting
1904 		    gui_stop_highlight(arg1);
1905 		    break;
1906 		case 'f':	// flash the window (visual bell)
1907 		    gui_mch_flash(arg1 == 0 ? 20 : arg1);
1908 		    break;
1909 		default:
1910 		    p = s + 1;	// Skip the ESC
1911 		    break;
1912 	    }
1913 	    len -= (int)(++p - s);
1914 	    s = p;
1915 	}
1916 	else if (
1917 #ifdef EBCDIC
1918 		CtrlChar(s[0]) != 0	// Ctrl character
1919 #else
1920 		s[0] < 0x20		// Ctrl character
1921 #endif
1922 #ifdef FEAT_SIGN_ICONS
1923 		&& s[0] != SIGN_BYTE
1924 # ifdef FEAT_NETBEANS_INTG
1925 		&& s[0] != MULTISIGN_BYTE
1926 # endif
1927 #endif
1928 		)
1929 	{
1930 	    if (s[0] == '\n')		// NL
1931 	    {
1932 		gui.col = 0;
1933 		if (gui.row < gui.scroll_region_bot)
1934 		    gui.row++;
1935 		else
1936 		    gui_delete_lines(gui.scroll_region_top, 1);
1937 	    }
1938 	    else if (s[0] == '\r')	// CR
1939 	    {
1940 		gui.col = 0;
1941 	    }
1942 	    else if (s[0] == '\b')	// Backspace
1943 	    {
1944 		if (gui.col)
1945 		    --gui.col;
1946 	    }
1947 	    else if (s[0] == Ctrl_L)	// cursor-right
1948 	    {
1949 		++gui.col;
1950 	    }
1951 	    else if (s[0] == Ctrl_G)	// Beep
1952 	    {
1953 		gui_mch_beep();
1954 	    }
1955 	    // Other Ctrl character: shouldn't happen!
1956 
1957 	    --len;	// Skip this char
1958 	    ++s;
1959 	}
1960 	else
1961 	{
1962 	    p = s;
1963 	    while (len > 0 && (
1964 #ifdef EBCDIC
1965 			CtrlChar(*p) == 0
1966 #else
1967 			*p >= 0x20
1968 #endif
1969 #ifdef FEAT_SIGN_ICONS
1970 			|| *p == SIGN_BYTE
1971 # ifdef FEAT_NETBEANS_INTG
1972 			|| *p == MULTISIGN_BYTE
1973 # endif
1974 #endif
1975 			))
1976 	    {
1977 		len--;
1978 		p++;
1979 	    }
1980 	    gui_outstr(s, (int)(p - s));
1981 	    s = p;
1982 	}
1983     }
1984 
1985     // Postponed update of the cursor (won't work if "can_update_cursor" isn't
1986     // set).
1987     if (force_cursor)
1988 	gui_update_cursor(TRUE, TRUE);
1989 
1990     // When switching to another window the dragging must have stopped.
1991     // Required for GTK, dragged_sb isn't reset.
1992     if (old_curwin != curwin)
1993 	gui.dragged_sb = SBAR_NONE;
1994 
1995     // Update the scrollbars after clearing the screen or when switched
1996     // to another window.
1997     // Update the horizontal scrollbar always, it's difficult to check all
1998     // situations where it might change.
1999     if (force_scrollbar || old_curwin != curwin)
2000 	gui_update_scrollbars(force_scrollbar);
2001     else
2002 	gui_update_horiz_scrollbar(FALSE);
2003     old_curwin = curwin;
2004 
2005     /*
2006      * We need to make sure this is cleared since Athena doesn't tell us when
2007      * he is done dragging.  Do the same for GTK.
2008      */
2009 #if defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_GTK)
2010     gui.dragged_sb = SBAR_NONE;
2011 #endif
2012 
2013     gui_may_flush();		    // In case vim decides to take a nap
2014 }
2015 
2016 /*
2017  * When ScreenLines[] is invalid, updating the cursor should not be done, it
2018  * produces wrong results.  Call gui_dont_update_cursor() before that code and
2019  * gui_can_update_cursor() afterwards.
2020  */
2021     void
2022 gui_dont_update_cursor(int undraw)
2023 {
2024     if (gui.in_use)
2025     {
2026 	// Undraw the cursor now, we probably can't do it after the change.
2027 	if (undraw)
2028 	    gui_undraw_cursor();
2029 	can_update_cursor = FALSE;
2030     }
2031 }
2032 
2033     void
2034 gui_can_update_cursor(void)
2035 {
2036     can_update_cursor = TRUE;
2037     // No need to update the cursor right now, there is always more output
2038     // after scrolling.
2039 }
2040 
2041 /*
2042  * Disable issuing gui_mch_flush().
2043  */
2044     void
2045 gui_disable_flush(void)
2046 {
2047     ++disable_flush;
2048 }
2049 
2050 /*
2051  * Enable issuing gui_mch_flush().
2052  */
2053     void
2054 gui_enable_flush(void)
2055 {
2056     --disable_flush;
2057 }
2058 
2059 /*
2060  * Issue gui_mch_flush() if it is not disabled.
2061  */
2062     void
2063 gui_may_flush(void)
2064 {
2065     if (disable_flush == 0)
2066 	gui_mch_flush();
2067 }
2068 
2069     static void
2070 gui_outstr(char_u *s, int len)
2071 {
2072     int	    this_len;
2073     int	    cells;
2074 
2075     if (len == 0)
2076 	return;
2077 
2078     if (len < 0)
2079 	len = (int)STRLEN(s);
2080 
2081     while (len > 0)
2082     {
2083 	if (has_mbyte)
2084 	{
2085 	    // Find out how many chars fit in the current line.
2086 	    cells = 0;
2087 	    for (this_len = 0; this_len < len; )
2088 	    {
2089 		cells += (*mb_ptr2cells)(s + this_len);
2090 		if (gui.col + cells > Columns)
2091 		    break;
2092 		this_len += (*mb_ptr2len)(s + this_len);
2093 	    }
2094 	    if (this_len > len)
2095 		this_len = len;	    // don't include following composing char
2096 	}
2097 	else
2098 	    if (gui.col + len > Columns)
2099 	    this_len = Columns - gui.col;
2100 	else
2101 	    this_len = len;
2102 
2103 	(void)gui_outstr_nowrap(s, this_len,
2104 					  0, (guicolor_T)0, (guicolor_T)0, 0);
2105 	s += this_len;
2106 	len -= this_len;
2107 	// fill up for a double-width char that doesn't fit.
2108 	if (len > 0 && gui.col < Columns)
2109 	    (void)gui_outstr_nowrap((char_u *)" ", 1,
2110 					  0, (guicolor_T)0, (guicolor_T)0, 0);
2111 	// The cursor may wrap to the next line.
2112 	if (gui.col >= Columns)
2113 	{
2114 	    gui.col = 0;
2115 	    gui.row++;
2116 	}
2117     }
2118 }
2119 
2120 /*
2121  * Output one character (may be one or two display cells).
2122  * Caller must check for valid "off".
2123  * Returns FAIL or OK, just like gui_outstr_nowrap().
2124  */
2125     static int
2126 gui_screenchar(
2127     int		off,	    // Offset from start of screen
2128     int		flags,
2129     guicolor_T	fg,	    // colors for cursor
2130     guicolor_T	bg,	    // colors for cursor
2131     int		back)	    // backup this many chars when using bold trick
2132 {
2133     char_u	buf[MB_MAXBYTES + 1];
2134 
2135     // Don't draw right halve of a double-width UTF-8 char. "cannot happen"
2136     if (enc_utf8 && ScreenLines[off] == 0)
2137 	return OK;
2138 
2139     if (enc_utf8 && ScreenLinesUC[off] != 0)
2140 	// Draw UTF-8 multi-byte character.
2141 	return gui_outstr_nowrap(buf, utfc_char2bytes(off, buf),
2142 							 flags, fg, bg, back);
2143 
2144     if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e)
2145     {
2146 	buf[0] = ScreenLines[off];
2147 	buf[1] = ScreenLines2[off];
2148 	return gui_outstr_nowrap(buf, 2, flags, fg, bg, back);
2149     }
2150 
2151     // Draw non-multi-byte character or DBCS character.
2152     return gui_outstr_nowrap(ScreenLines + off,
2153 	    enc_dbcs ? (*mb_ptr2len)(ScreenLines + off) : 1,
2154 							 flags, fg, bg, back);
2155 }
2156 
2157 #ifdef FEAT_GUI_GTK
2158 /*
2159  * Output the string at the given screen position.  This is used in place
2160  * of gui_screenchar() where possible because Pango needs as much context
2161  * as possible to work nicely.  It's a lot faster as well.
2162  */
2163     static int
2164 gui_screenstr(
2165     int		off,	    // Offset from start of screen
2166     int		len,	    // string length in screen cells
2167     int		flags,
2168     guicolor_T	fg,	    // colors for cursor
2169     guicolor_T	bg,	    // colors for cursor
2170     int		back)	    // backup this many chars when using bold trick
2171 {
2172     char_u  *buf;
2173     int	    outlen = 0;
2174     int	    i;
2175     int	    retval;
2176 
2177     if (len <= 0) // "cannot happen"?
2178 	return OK;
2179 
2180     if (enc_utf8)
2181     {
2182 	buf = alloc(len * MB_MAXBYTES + 1);
2183 	if (buf == NULL)
2184 	    return OK; // not much we could do here...
2185 
2186 	for (i = off; i < off + len; ++i)
2187 	{
2188 	    if (ScreenLines[i] == 0)
2189 		continue; // skip second half of double-width char
2190 
2191 	    if (ScreenLinesUC[i] == 0)
2192 		buf[outlen++] = ScreenLines[i];
2193 	    else
2194 		outlen += utfc_char2bytes(i, buf + outlen);
2195 	}
2196 
2197 	buf[outlen] = NUL; // only to aid debugging
2198 	retval = gui_outstr_nowrap(buf, outlen, flags, fg, bg, back);
2199 	vim_free(buf);
2200 
2201 	return retval;
2202     }
2203     else if (enc_dbcs == DBCS_JPNU)
2204     {
2205 	buf = alloc(len * 2 + 1);
2206 	if (buf == NULL)
2207 	    return OK; // not much we could do here...
2208 
2209 	for (i = off; i < off + len; ++i)
2210 	{
2211 	    buf[outlen++] = ScreenLines[i];
2212 
2213 	    // handle double-byte single-width char
2214 	    if (ScreenLines[i] == 0x8e)
2215 		buf[outlen++] = ScreenLines2[i];
2216 	    else if (MB_BYTE2LEN(ScreenLines[i]) == 2)
2217 		buf[outlen++] = ScreenLines[++i];
2218 	}
2219 
2220 	buf[outlen] = NUL; // only to aid debugging
2221 	retval = gui_outstr_nowrap(buf, outlen, flags, fg, bg, back);
2222 	vim_free(buf);
2223 
2224 	return retval;
2225     }
2226     else
2227     {
2228 	return gui_outstr_nowrap(&ScreenLines[off], len,
2229 				 flags, fg, bg, back);
2230     }
2231 }
2232 #endif // FEAT_GUI_GTK
2233 
2234 /*
2235  * Output the given string at the current cursor position.  If the string is
2236  * too long to fit on the line, then it is truncated.
2237  * "flags":
2238  * GUI_MON_IS_CURSOR should only be used when this function is being called to
2239  * actually draw (an inverted) cursor.
2240  * GUI_MON_TRS_CURSOR is used to draw the cursor text with a transparent
2241  * background.
2242  * GUI_MON_NOCLEAR is used to avoid clearing the selection when drawing over
2243  * it.
2244  * Returns OK, unless "back" is non-zero and using the bold trick, then return
2245  * FAIL (the caller should start drawing "back" chars back).
2246  */
2247     static int
2248 gui_outstr_nowrap(
2249     char_u	*s,
2250     int		len,
2251     int		flags,
2252     guicolor_T	fg,	    // colors for cursor
2253     guicolor_T	bg,	    // colors for cursor
2254     int		back)	    // backup this many chars when using bold trick
2255 {
2256     long_u	highlight_mask;
2257     long_u	hl_mask_todo;
2258     guicolor_T	fg_color;
2259     guicolor_T	bg_color;
2260     guicolor_T	sp_color;
2261 #if !defined(FEAT_GUI_GTK)
2262     GuiFont	font = NOFONT;
2263     GuiFont	wide_font = NOFONT;
2264 # ifdef FEAT_XFONTSET
2265     GuiFontset	fontset = NOFONTSET;
2266 # endif
2267 #endif
2268     attrentry_T	*aep = NULL;
2269     int		draw_flags;
2270     int		col = gui.col;
2271 #ifdef FEAT_SIGN_ICONS
2272     int		draw_sign = FALSE;
2273     int		signcol = 0;
2274     char_u	extra[18];
2275 # ifdef FEAT_NETBEANS_INTG
2276     int		multi_sign = FALSE;
2277 # endif
2278 #endif
2279 
2280     if (len < 0)
2281 	len = (int)STRLEN(s);
2282     if (len == 0)
2283 	return OK;
2284 
2285 #ifdef FEAT_SIGN_ICONS
2286     if (*s == SIGN_BYTE
2287 # ifdef FEAT_NETBEANS_INTG
2288 	  || *s == MULTISIGN_BYTE
2289 # endif
2290        )
2291     {
2292 # ifdef FEAT_NETBEANS_INTG
2293 	if (*s == MULTISIGN_BYTE)
2294 	    multi_sign = TRUE;
2295 # endif
2296 	// draw spaces instead
2297 	if (*curwin->w_p_scl == 'n' && *(curwin->w_p_scl + 1) == 'u' &&
2298 		(curwin->w_p_nu || curwin->w_p_rnu))
2299 	{
2300 	    sprintf((char *)extra, "%*c ", number_width(curwin), ' ');
2301 	    s = extra;
2302 	}
2303 	else
2304 	    s = (char_u *)"  ";
2305 	if (len == 1 && col > 0)
2306 	    --col;
2307 	len = (int)STRLEN(s);
2308 	if (len > 2)
2309 	    // right align sign icon in the number column
2310 	    signcol = col + len - 3;
2311 	else
2312 	    signcol = col;
2313 	draw_sign = TRUE;
2314 	highlight_mask = 0;
2315     }
2316     else
2317 #endif
2318     if (gui.highlight_mask > HL_ALL)
2319     {
2320 	aep = syn_gui_attr2entry(gui.highlight_mask);
2321 	if (aep == NULL)	    // highlighting not set
2322 	    highlight_mask = 0;
2323 	else
2324 	    highlight_mask = aep->ae_attr;
2325     }
2326     else
2327 	highlight_mask = gui.highlight_mask;
2328     hl_mask_todo = highlight_mask;
2329 
2330 #if !defined(FEAT_GUI_GTK)
2331     // Set the font
2332     if (aep != NULL && aep->ae_u.gui.font != NOFONT)
2333 	font = aep->ae_u.gui.font;
2334 # ifdef FEAT_XFONTSET
2335     else if (aep != NULL && aep->ae_u.gui.fontset != NOFONTSET)
2336 	fontset = aep->ae_u.gui.fontset;
2337 # endif
2338     else
2339     {
2340 # ifdef FEAT_XFONTSET
2341 	if (gui.fontset != NOFONTSET)
2342 	    fontset = gui.fontset;
2343 	else
2344 # endif
2345 	    if (hl_mask_todo & (HL_BOLD | HL_STANDOUT))
2346 	{
2347 	    if ((hl_mask_todo & HL_ITALIC) && gui.boldital_font != NOFONT)
2348 	    {
2349 		font = gui.boldital_font;
2350 		hl_mask_todo &= ~(HL_BOLD | HL_STANDOUT | HL_ITALIC);
2351 	    }
2352 	    else if (gui.bold_font != NOFONT)
2353 	    {
2354 		font = gui.bold_font;
2355 		hl_mask_todo &= ~(HL_BOLD | HL_STANDOUT);
2356 	    }
2357 	    else
2358 		font = gui.norm_font;
2359 	}
2360 	else if ((hl_mask_todo & HL_ITALIC) && gui.ital_font != NOFONT)
2361 	{
2362 	    font = gui.ital_font;
2363 	    hl_mask_todo &= ~HL_ITALIC;
2364 	}
2365 	else
2366 	    font = gui.norm_font;
2367 
2368 	/*
2369 	 * Choose correct wide_font by font.  wide_font should be set with font
2370 	 * at same time in above block.  But it will make many "ifdef" nasty
2371 	 * blocks.  So we do it here.
2372 	 */
2373 	if (font == gui.boldital_font && gui.wide_boldital_font)
2374 	    wide_font = gui.wide_boldital_font;
2375 	else if (font == gui.bold_font && gui.wide_bold_font)
2376 	    wide_font = gui.wide_bold_font;
2377 	else if (font == gui.ital_font && gui.wide_ital_font)
2378 	    wide_font = gui.wide_ital_font;
2379 	else if (font == gui.norm_font && gui.wide_font)
2380 	    wide_font = gui.wide_font;
2381     }
2382 # ifdef FEAT_XFONTSET
2383     if (fontset != NOFONTSET)
2384 	gui_mch_set_fontset(fontset);
2385     else
2386 # endif
2387 	gui_mch_set_font(font);
2388 #endif
2389 
2390     draw_flags = 0;
2391 
2392     // Set the color
2393     bg_color = gui.back_pixel;
2394     if ((flags & GUI_MON_IS_CURSOR) && gui.in_focus)
2395     {
2396 	draw_flags |= DRAW_CURSOR;
2397 	fg_color = fg;
2398 	bg_color = bg;
2399 	sp_color = fg;
2400     }
2401     else if (aep != NULL)
2402     {
2403 	fg_color = aep->ae_u.gui.fg_color;
2404 	if (fg_color == INVALCOLOR)
2405 	    fg_color = gui.norm_pixel;
2406 	bg_color = aep->ae_u.gui.bg_color;
2407 	if (bg_color == INVALCOLOR)
2408 	    bg_color = gui.back_pixel;
2409 	sp_color = aep->ae_u.gui.sp_color;
2410 	if (sp_color == INVALCOLOR)
2411 	    sp_color = fg_color;
2412     }
2413     else
2414     {
2415 	fg_color = gui.norm_pixel;
2416 	sp_color = fg_color;
2417     }
2418 
2419     if (highlight_mask & (HL_INVERSE | HL_STANDOUT))
2420     {
2421 	gui_mch_set_fg_color(bg_color);
2422 	gui_mch_set_bg_color(fg_color);
2423     }
2424     else
2425     {
2426 	gui_mch_set_fg_color(fg_color);
2427 	gui_mch_set_bg_color(bg_color);
2428     }
2429     gui_mch_set_sp_color(sp_color);
2430 
2431     // Clear the selection if we are about to write over it
2432     if (!(flags & GUI_MON_NOCLEAR))
2433 	clip_may_clear_selection(gui.row, gui.row);
2434 
2435 
2436     // If there's no bold font, then fake it
2437     if (hl_mask_todo & (HL_BOLD | HL_STANDOUT))
2438 	draw_flags |= DRAW_BOLD;
2439 
2440     /*
2441      * When drawing bold or italic characters the spill-over from the left
2442      * neighbor may be destroyed.  Let the caller backup to start redrawing
2443      * just after a blank.
2444      */
2445     if (back != 0 && ((draw_flags & DRAW_BOLD) || (highlight_mask & HL_ITALIC)))
2446 	return FAIL;
2447 
2448 #if defined(FEAT_GUI_GTK)
2449     // If there's no italic font, then fake it.
2450     // For GTK2, we don't need a different font for italic style.
2451     if (hl_mask_todo & HL_ITALIC)
2452 	draw_flags |= DRAW_ITALIC;
2453 
2454     // Do we underline the text?
2455     if (hl_mask_todo & HL_UNDERLINE)
2456 	draw_flags |= DRAW_UNDERL;
2457 
2458 #else
2459     // Do we underline the text?
2460     if ((hl_mask_todo & HL_UNDERLINE) || (hl_mask_todo & HL_ITALIC))
2461 	draw_flags |= DRAW_UNDERL;
2462 #endif
2463     // Do we undercurl the text?
2464     if (hl_mask_todo & HL_UNDERCURL)
2465 	draw_flags |= DRAW_UNDERC;
2466 
2467     // Do we strikethrough the text?
2468     if (hl_mask_todo & HL_STRIKETHROUGH)
2469 	draw_flags |= DRAW_STRIKE;
2470 
2471     // Do we draw transparently?
2472     if (flags & GUI_MON_TRS_CURSOR)
2473 	draw_flags |= DRAW_TRANSP;
2474 
2475     /*
2476      * Draw the text.
2477      */
2478 #ifdef FEAT_GUI_GTK
2479     // The value returned is the length in display cells
2480     len = gui_gtk2_draw_string(gui.row, col, s, len, draw_flags);
2481 #else
2482     if (enc_utf8)
2483     {
2484 	int	start;		// index of bytes to be drawn
2485 	int	cells;		// cellwidth of bytes to be drawn
2486 	int	thislen;	// length of bytes to be drawn
2487 	int	cn;		// cellwidth of current char
2488 	int	i;		// index of current char
2489 	int	c;		// current char value
2490 	int	cl;		// byte length of current char
2491 	int	comping;	// current char is composing
2492 	int	scol = col;	// screen column
2493 	int	curr_wide = FALSE;  // use 'guifontwide'
2494 	int	prev_wide = FALSE;
2495 	int	wide_changed;
2496 # ifdef MSWIN
2497 	int	sep_comp = FALSE;   // Don't separate composing chars.
2498 # else
2499 	int	sep_comp = TRUE;    // Separate composing chars.
2500 # endif
2501 
2502 	// Break the string at a composing character, it has to be drawn on
2503 	// top of the previous character.
2504 	start = 0;
2505 	cells = 0;
2506 	for (i = 0; i < len; i += cl)
2507 	{
2508 	    c = utf_ptr2char(s + i);
2509 	    cn = utf_char2cells(c);
2510 	    comping = utf_iscomposing(c);
2511 	    if (!comping)	// count cells from non-composing chars
2512 		cells += cn;
2513 	    if (!comping || sep_comp)
2514 	    {
2515 		if (cn > 1
2516 # ifdef FEAT_XFONTSET
2517 			&& fontset == NOFONTSET
2518 # endif
2519 			&& wide_font != NOFONT)
2520 		    curr_wide = TRUE;
2521 		else
2522 		    curr_wide = FALSE;
2523 	    }
2524 	    cl = utf_ptr2len(s + i);
2525 	    if (cl == 0)	// hit end of string
2526 		len = i + cl;	// len must be wrong "cannot happen"
2527 
2528 	    wide_changed = curr_wide != prev_wide;
2529 
2530 	    // Print the string so far if it's the last character or there is
2531 	    // a composing character.
2532 	    if (i + cl >= len || (comping && sep_comp && i > start)
2533 		    || wide_changed
2534 # if defined(FEAT_GUI_X11)
2535 		    || (cn > 1
2536 #  ifdef FEAT_XFONTSET
2537 			// No fontset: At least draw char after wide char at
2538 			// right position.
2539 			&& fontset == NOFONTSET
2540 #  endif
2541 		       )
2542 # endif
2543 	       )
2544 	    {
2545 		if ((comping && sep_comp) || wide_changed)
2546 		    thislen = i - start;
2547 		else
2548 		    thislen = i - start + cl;
2549 		if (thislen > 0)
2550 		{
2551 		    if (prev_wide)
2552 			gui_mch_set_font(wide_font);
2553 		    gui_mch_draw_string(gui.row, scol, s + start, thislen,
2554 								  draw_flags);
2555 		    if (prev_wide)
2556 			gui_mch_set_font(font);
2557 		    start += thislen;
2558 		}
2559 		scol += cells;
2560 		cells = 0;
2561 		// Adjust to not draw a character which width is changed
2562 		// against with last one.
2563 		if (wide_changed && !(comping && sep_comp))
2564 		{
2565 		    scol -= cn;
2566 		    cl = 0;
2567 		}
2568 
2569 # if defined(FEAT_GUI_X11)
2570 		// No fontset: draw a space to fill the gap after a wide char
2571 		//
2572 		if (cn > 1 && (draw_flags & DRAW_TRANSP) == 0
2573 #  ifdef FEAT_XFONTSET
2574 			&& fontset == NOFONTSET
2575 #  endif
2576 			&& !wide_changed)
2577 		    gui_mch_draw_string(gui.row, scol - 1, (char_u *)" ",
2578 							       1, draw_flags);
2579 # endif
2580 	    }
2581 	    // Draw a composing char on top of the previous char.
2582 	    if (comping && sep_comp)
2583 	    {
2584 # if defined(__APPLE_CC__) && TARGET_API_MAC_CARBON
2585 		// Carbon ATSUI autodraws composing char over previous char
2586 		gui_mch_draw_string(gui.row, scol, s + i, cl,
2587 						    draw_flags | DRAW_TRANSP);
2588 # else
2589 		gui_mch_draw_string(gui.row, scol - cn, s + i, cl,
2590 						    draw_flags | DRAW_TRANSP);
2591 # endif
2592 		start = i + cl;
2593 	    }
2594 	    prev_wide = curr_wide;
2595 	}
2596 	// The stuff below assumes "len" is the length in screen columns.
2597 	len = scol - col;
2598     }
2599     else
2600     {
2601 	gui_mch_draw_string(gui.row, col, s, len, draw_flags);
2602 	if (enc_dbcs == DBCS_JPNU)
2603 	{
2604 	    // Get the length in display cells, this can be different from the
2605 	    // number of bytes for "euc-jp".
2606 	    len = mb_string2cells(s, len);
2607 	}
2608     }
2609 #endif // !FEAT_GUI_GTK
2610 
2611     if (!(flags & (GUI_MON_IS_CURSOR | GUI_MON_TRS_CURSOR)))
2612 	gui.col = col + len;
2613 
2614     // May need to invert it when it's part of the selection.
2615     if (flags & GUI_MON_NOCLEAR)
2616 	clip_may_redraw_selection(gui.row, col, len);
2617 
2618     if (!(flags & (GUI_MON_IS_CURSOR | GUI_MON_TRS_CURSOR)))
2619     {
2620 	// Invalidate the old physical cursor position if we wrote over it
2621 	if (gui.cursor_row == gui.row
2622 		&& gui.cursor_col >= col
2623 		&& gui.cursor_col < col + len)
2624 	    gui.cursor_is_valid = FALSE;
2625     }
2626 
2627 #ifdef FEAT_SIGN_ICONS
2628     if (draw_sign)
2629 	// Draw the sign on top of the spaces.
2630 	gui_mch_drawsign(gui.row, signcol, gui.highlight_mask);
2631 # if defined(FEAT_NETBEANS_INTG) && (defined(FEAT_GUI_X11) \
2632 	|| defined(FEAT_GUI_GTK) || defined(FEAT_GUI_MSWIN))
2633     if (multi_sign)
2634 	netbeans_draw_multisign_indicator(gui.row);
2635 # endif
2636 #endif
2637 
2638     return OK;
2639 }
2640 
2641 /*
2642  * Un-draw the cursor.	Actually this just redraws the character at the given
2643  * position.
2644  */
2645     void
2646 gui_undraw_cursor(void)
2647 {
2648     if (gui.cursor_is_valid)
2649     {
2650 	// Redraw the character just before too, if there is one, because with
2651 	// some fonts and characters there can be a one pixel overlap.
2652 	gui_redraw_block(gui.cursor_row,
2653 		      gui.cursor_col > 0 ? gui.cursor_col - 1 : gui.cursor_col,
2654 		      gui.cursor_row, gui.cursor_col, GUI_MON_NOCLEAR);
2655 
2656 	// Cursor_is_valid is reset when the cursor is undrawn, also reset it
2657 	// here in case it wasn't needed to undraw it.
2658 	gui.cursor_is_valid = FALSE;
2659     }
2660 }
2661 
2662     void
2663 gui_redraw(
2664     int		x,
2665     int		y,
2666     int		w,
2667     int		h)
2668 {
2669     int		row1, col1, row2, col2;
2670 
2671     row1 = Y_2_ROW(y);
2672     col1 = X_2_COL(x);
2673     row2 = Y_2_ROW(y + h - 1);
2674     col2 = X_2_COL(x + w - 1);
2675 
2676     gui_redraw_block(row1, col1, row2, col2, GUI_MON_NOCLEAR);
2677 
2678     /*
2679      * We may need to redraw the cursor, but don't take it upon us to change
2680      * its location after a scroll.
2681      * (maybe be more strict even and test col too?)
2682      * These things may be outside the update/clipping region and reality may
2683      * not reflect Vims internal ideas if these operations are clipped away.
2684      */
2685     if (gui.row == gui.cursor_row)
2686 	gui_update_cursor(TRUE, TRUE);
2687 }
2688 
2689 /*
2690  * Draw a rectangular block of characters, from row1 to row2 (inclusive) and
2691  * from col1 to col2 (inclusive).
2692  */
2693     void
2694 gui_redraw_block(
2695     int		row1,
2696     int		col1,
2697     int		row2,
2698     int		col2,
2699     int		flags)	// flags for gui_outstr_nowrap()
2700 {
2701     int		old_row, old_col;
2702     long_u	old_hl_mask;
2703     int		off;
2704     sattr_T	first_attr;
2705     int		idx, len;
2706     int		back, nback;
2707     int		orig_col1, orig_col2;
2708 
2709     // Don't try to update when ScreenLines is not valid
2710     if (!screen_cleared || ScreenLines == NULL)
2711 	return;
2712 
2713     // Don't try to draw outside the shell!
2714     // Check everything, strange values may be caused by a big border width
2715     col1 = check_col(col1);
2716     col2 = check_col(col2);
2717     row1 = check_row(row1);
2718     row2 = check_row(row2);
2719 
2720     // Remember where our cursor was
2721     old_row = gui.row;
2722     old_col = gui.col;
2723     old_hl_mask = gui.highlight_mask;
2724     orig_col1 = col1;
2725     orig_col2 = col2;
2726 
2727     for (gui.row = row1; gui.row <= row2; gui.row++)
2728     {
2729 	// When only half of a double-wide character is in the block, include
2730 	// the other half.
2731 	col1 = orig_col1;
2732 	col2 = orig_col2;
2733 	off = LineOffset[gui.row];
2734 	if (enc_dbcs != 0)
2735 	{
2736 	    if (col1 > 0)
2737 		col1 -= dbcs_screen_head_off(ScreenLines + off,
2738 						    ScreenLines + off + col1);
2739 	    col2 += dbcs_screen_tail_off(ScreenLines + off,
2740 						    ScreenLines + off + col2);
2741 	}
2742 	else if (enc_utf8)
2743 	{
2744 	    if (ScreenLines[off + col1] == 0)
2745 	    {
2746 		if (col1 > 0)
2747 		    --col1;
2748 		else
2749 		{
2750 		    // FIXME: how can the first character ever be zero?
2751 		    // Make this IEMSGN when it no longer breaks Travis CI.
2752 		    vim_snprintf((char *)IObuff, IOSIZE,
2753 			    "INTERNAL ERROR: NUL in ScreenLines in row %ld",
2754 			    (long)gui.row);
2755 		    msg((char *)IObuff);
2756 		}
2757 	    }
2758 #ifdef FEAT_GUI_GTK
2759 	    if (col2 + 1 < Columns && ScreenLines[off + col2 + 1] == 0)
2760 		++col2;
2761 #endif
2762 	}
2763 	gui.col = col1;
2764 	off = LineOffset[gui.row] + gui.col;
2765 	len = col2 - col1 + 1;
2766 
2767 	// Find how many chars back this highlighting starts, or where a space
2768 	// is.  Needed for when the bold trick is used
2769 	for (back = 0; back < col1; ++back)
2770 	    if (ScreenAttrs[off - 1 - back] != ScreenAttrs[off]
2771 		    || ScreenLines[off - 1 - back] == ' ')
2772 		break;
2773 
2774 	// Break it up in strings of characters with the same attributes.
2775 	// Print UTF-8 characters individually.
2776 	while (len > 0)
2777 	{
2778 	    first_attr = ScreenAttrs[off];
2779 	    gui.highlight_mask = first_attr;
2780 #if !defined(FEAT_GUI_GTK)
2781 	    if (enc_utf8 && ScreenLinesUC[off] != 0)
2782 	    {
2783 		// output multi-byte character separately
2784 		nback = gui_screenchar(off, flags,
2785 					  (guicolor_T)0, (guicolor_T)0, back);
2786 		if (gui.col < Columns && ScreenLines[off + 1] == 0)
2787 		    idx = 2;
2788 		else
2789 		    idx = 1;
2790 	    }
2791 	    else if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e)
2792 	    {
2793 		// output double-byte, single-width character separately
2794 		nback = gui_screenchar(off, flags,
2795 					  (guicolor_T)0, (guicolor_T)0, back);
2796 		idx = 1;
2797 	    }
2798 	    else
2799 #endif
2800 	    {
2801 #ifdef FEAT_GUI_GTK
2802 		for (idx = 0; idx < len; ++idx)
2803 		{
2804 		    if (enc_utf8 && ScreenLines[off + idx] == 0)
2805 			continue; // skip second half of double-width char
2806 		    if (ScreenAttrs[off + idx] != first_attr)
2807 			break;
2808 		}
2809 		// gui_screenstr() takes care of multibyte chars
2810 		nback = gui_screenstr(off, idx, flags,
2811 				      (guicolor_T)0, (guicolor_T)0, back);
2812 #else
2813 		for (idx = 0; idx < len && ScreenAttrs[off + idx] == first_attr;
2814 									idx++)
2815 		{
2816 		    // Stop at a multi-byte Unicode character.
2817 		    if (enc_utf8 && ScreenLinesUC[off + idx] != 0)
2818 			break;
2819 		    if (enc_dbcs == DBCS_JPNU)
2820 		    {
2821 			// Stop at a double-byte single-width char.
2822 			if (ScreenLines[off + idx] == 0x8e)
2823 			    break;
2824 			if (len > 1 && (*mb_ptr2len)(ScreenLines
2825 							    + off + idx) == 2)
2826 			    ++idx;  // skip second byte of double-byte char
2827 		    }
2828 		}
2829 		nback = gui_outstr_nowrap(ScreenLines + off, idx, flags,
2830 					  (guicolor_T)0, (guicolor_T)0, back);
2831 #endif
2832 	    }
2833 	    if (nback == FAIL)
2834 	    {
2835 		// Must back up to start drawing where a bold or italic word
2836 		// starts.
2837 		off -= back;
2838 		len += back;
2839 		gui.col -= back;
2840 	    }
2841 	    else
2842 	    {
2843 		off += idx;
2844 		len -= idx;
2845 	    }
2846 	    back = 0;
2847 	}
2848     }
2849 
2850     // Put the cursor back where it was
2851     gui.row = old_row;
2852     gui.col = old_col;
2853     gui.highlight_mask = (int)old_hl_mask;
2854 }
2855 
2856     static void
2857 gui_delete_lines(int row, int count)
2858 {
2859     if (count <= 0)
2860 	return;
2861 
2862     if (row + count > gui.scroll_region_bot)
2863 	// Scrolled out of region, just blank the lines out
2864 	gui_clear_block(row, gui.scroll_region_left,
2865 			      gui.scroll_region_bot, gui.scroll_region_right);
2866     else
2867     {
2868 	gui_mch_delete_lines(row, count);
2869 
2870 	// If the cursor was in the deleted lines it's now gone.  If the
2871 	// cursor was in the scrolled lines adjust its position.
2872 	if (gui.cursor_row >= row
2873 		&& gui.cursor_col >= gui.scroll_region_left
2874 		&& gui.cursor_col <= gui.scroll_region_right)
2875 	{
2876 	    if (gui.cursor_row < row + count)
2877 		gui.cursor_is_valid = FALSE;
2878 	    else if (gui.cursor_row <= gui.scroll_region_bot)
2879 		gui.cursor_row -= count;
2880 	}
2881     }
2882 }
2883 
2884     static void
2885 gui_insert_lines(int row, int count)
2886 {
2887     if (count <= 0)
2888 	return;
2889 
2890     if (row + count > gui.scroll_region_bot)
2891 	// Scrolled out of region, just blank the lines out
2892 	gui_clear_block(row, gui.scroll_region_left,
2893 			      gui.scroll_region_bot, gui.scroll_region_right);
2894     else
2895     {
2896 	gui_mch_insert_lines(row, count);
2897 
2898 	if (gui.cursor_row >= gui.row
2899 		&& gui.cursor_col >= gui.scroll_region_left
2900 		&& gui.cursor_col <= gui.scroll_region_right)
2901 	{
2902 	    if (gui.cursor_row <= gui.scroll_region_bot - count)
2903 		gui.cursor_row += count;
2904 	    else if (gui.cursor_row <= gui.scroll_region_bot)
2905 		gui.cursor_is_valid = FALSE;
2906 	}
2907     }
2908 }
2909 
2910 #ifdef FEAT_TIMERS
2911 /*
2912  * Passed to ui_wait_for_chars_or_timer(), ignoring extra arguments.
2913  */
2914     static int
2915 gui_wait_for_chars_3(
2916     long wtime,
2917     int *interrupted UNUSED,
2918     int ignore_input UNUSED)
2919 {
2920     return gui_mch_wait_for_chars(wtime);
2921 }
2922 #endif
2923 
2924 /*
2925  * Returns OK if a character was found to be available within the given time,
2926  * or FAIL otherwise.
2927  */
2928     static int
2929 gui_wait_for_chars_or_timer(
2930 	long wtime,
2931 	int *interrupted UNUSED,
2932 	int ignore_input UNUSED)
2933 {
2934 #ifdef FEAT_TIMERS
2935     return ui_wait_for_chars_or_timer(wtime, gui_wait_for_chars_3,
2936 						    interrupted, ignore_input);
2937 #else
2938     return gui_mch_wait_for_chars(wtime);
2939 #endif
2940 }
2941 
2942 /*
2943  * The main GUI input routine.	Waits for a character from the keyboard.
2944  * "wtime" == -1    Wait forever.
2945  * "wtime" == 0	    Don't wait.
2946  * "wtime" > 0	    Wait wtime milliseconds for a character.
2947  *
2948  * Returns the number of characters read or zero when timed out or interrupted.
2949  * "buf" may be NULL, in which case a non-zero number is returned if characters
2950  * are available.
2951  */
2952     static int
2953 gui_wait_for_chars_buf(
2954     char_u	*buf,
2955     int		maxlen,
2956     long	wtime,	    // don't use "time", MIPS cannot handle it
2957     int		tb_change_cnt)
2958 {
2959     int	    retval;
2960 
2961 #ifdef FEAT_MENU
2962     // If we're going to wait a bit, update the menus and mouse shape for the
2963     // current State.
2964     if (wtime != 0)
2965 	gui_update_menus(0);
2966 #endif
2967 
2968     gui_mch_update();
2969     if (input_available())	// Got char, return immediately
2970     {
2971 	if (buf != NULL && !typebuf_changed(tb_change_cnt))
2972 	    return read_from_input_buf(buf, (long)maxlen);
2973 	return 0;
2974     }
2975     if (wtime == 0)		// Don't wait for char
2976 	return FAIL;
2977 
2978     // Before waiting, flush any output to the screen.
2979     gui_mch_flush();
2980 
2981     // Blink while waiting for a character.
2982     gui_mch_start_blink();
2983 
2984     // Common function to loop until "wtime" is met, while handling timers and
2985     // other callbacks.
2986     retval = inchar_loop(buf, maxlen, wtime, tb_change_cnt,
2987 			 gui_wait_for_chars_or_timer, NULL);
2988 
2989     gui_mch_stop_blink(TRUE);
2990 
2991     return retval;
2992 }
2993 
2994 /*
2995  * Wait for a character from the keyboard without actually reading it.
2996  * Also deals with timers.
2997  * wtime == -1	    Wait forever.
2998  * wtime == 0	    Don't wait.
2999  * wtime > 0	    Wait wtime milliseconds for a character.
3000  * Returns OK if a character was found to be available within the given time,
3001  * or FAIL otherwise.
3002  */
3003     int
3004 gui_wait_for_chars(long wtime, int tb_change_cnt)
3005 {
3006     return gui_wait_for_chars_buf(NULL, 0, wtime, tb_change_cnt);
3007 }
3008 
3009 /*
3010  * Equivalent of mch_inchar() for the GUI.
3011  */
3012     int
3013 gui_inchar(
3014     char_u  *buf,
3015     int	    maxlen,
3016     long    wtime,		// milli seconds
3017     int	    tb_change_cnt)
3018 {
3019     return gui_wait_for_chars_buf(buf, maxlen, wtime, tb_change_cnt);
3020 }
3021 
3022 /*
3023  * Fill p[4] with mouse coordinates encoded for check_termcode().
3024  */
3025     static void
3026 fill_mouse_coord(char_u *p, int col, int row)
3027 {
3028     p[0] = (char_u)(col / 128 + ' ' + 1);
3029     p[1] = (char_u)(col % 128 + ' ' + 1);
3030     p[2] = (char_u)(row / 128 + ' ' + 1);
3031     p[3] = (char_u)(row % 128 + ' ' + 1);
3032 }
3033 
3034 /*
3035  * Generic mouse support function.  Add a mouse event to the input buffer with
3036  * the given properties.
3037  *  button	    --- may be any of MOUSE_LEFT, MOUSE_MIDDLE, MOUSE_RIGHT,
3038  *			MOUSE_X1, MOUSE_X2
3039  *			MOUSE_DRAG, or MOUSE_RELEASE.
3040  *			MOUSE_4 and MOUSE_5 are used for vertical scroll wheel,
3041  *			MOUSE_6 and MOUSE_7 for horizontal scroll wheel.
3042  *  x, y	    --- Coordinates of mouse in pixels.
3043  *  repeated_click  --- TRUE if this click comes only a short time after a
3044  *			previous click.
3045  *  modifiers	    --- Bit field which may be any of the following modifiers
3046  *			or'ed together: MOUSE_SHIFT | MOUSE_CTRL | MOUSE_ALT.
3047  * This function will ignore drag events where the mouse has not moved to a new
3048  * character.
3049  */
3050     void
3051 gui_send_mouse_event(
3052     int	    button,
3053     int	    x,
3054     int	    y,
3055     int	    repeated_click,
3056     int_u   modifiers)
3057 {
3058     static int	    prev_row = 0, prev_col = 0;
3059     static int	    prev_button = -1;
3060     static int	    num_clicks = 1;
3061     char_u	    string[10];
3062     enum key_extra  button_char;
3063     int		    row, col;
3064 #ifdef FEAT_CLIPBOARD
3065     int		    checkfor;
3066     int		    did_clip = FALSE;
3067 #endif
3068 
3069     /*
3070      * Scrolling may happen at any time, also while a selection is present.
3071      */
3072     switch (button)
3073     {
3074 	case MOUSE_X1:
3075 	    button_char = KE_X1MOUSE;
3076 	    goto button_set;
3077 	case MOUSE_X2:
3078 	    button_char = KE_X2MOUSE;
3079 	    goto button_set;
3080 	case MOUSE_4:
3081 	    button_char = KE_MOUSEDOWN;
3082 	    goto button_set;
3083 	case MOUSE_5:
3084 	    button_char = KE_MOUSEUP;
3085 	    goto button_set;
3086 	case MOUSE_6:
3087 	    button_char = KE_MOUSELEFT;
3088 	    goto button_set;
3089 	case MOUSE_7:
3090 	    button_char = KE_MOUSERIGHT;
3091 button_set:
3092 	    {
3093 		// Don't put events in the input queue now.
3094 		if (hold_gui_events)
3095 		    return;
3096 
3097 		string[3] = CSI;
3098 		string[4] = KS_EXTRA;
3099 		string[5] = (int)button_char;
3100 
3101 		// Pass the pointer coordinates of the scroll event so that we
3102 		// know which window to scroll.
3103 		row = gui_xy2colrow(x, y, &col);
3104 		string[6] = (char_u)(col / 128 + ' ' + 1);
3105 		string[7] = (char_u)(col % 128 + ' ' + 1);
3106 		string[8] = (char_u)(row / 128 + ' ' + 1);
3107 		string[9] = (char_u)(row % 128 + ' ' + 1);
3108 
3109 		if (modifiers == 0)
3110 		    add_to_input_buf(string + 3, 7);
3111 		else
3112 		{
3113 		    string[0] = CSI;
3114 		    string[1] = KS_MODIFIER;
3115 		    string[2] = 0;
3116 		    if (modifiers & MOUSE_SHIFT)
3117 			string[2] |= MOD_MASK_SHIFT;
3118 		    if (modifiers & MOUSE_CTRL)
3119 			string[2] |= MOD_MASK_CTRL;
3120 		    if (modifiers & MOUSE_ALT)
3121 			string[2] |= MOD_MASK_ALT;
3122 		    add_to_input_buf(string, 10);
3123 		}
3124 		return;
3125 	    }
3126     }
3127 
3128 #ifdef FEAT_CLIPBOARD
3129     // If a clipboard selection is in progress, handle it
3130     if (clip_star.state == SELECT_IN_PROGRESS)
3131     {
3132 	clip_process_selection(button, X_2_COL(x), Y_2_ROW(y), repeated_click);
3133 
3134 	// A release event may still need to be sent if the position is equal.
3135 	row = gui_xy2colrow(x, y, &col);
3136 	if (button != MOUSE_RELEASE || row != prev_row || col != prev_col)
3137 	    return;
3138     }
3139 
3140     // Determine which mouse settings to look for based on the current mode
3141     switch (get_real_state())
3142     {
3143 	case NORMAL_BUSY:
3144 	case OP_PENDING:
3145 # ifdef FEAT_TERMINAL
3146 	case TERMINAL:
3147 # endif
3148 	case NORMAL:		checkfor = MOUSE_NORMAL;	break;
3149 	case VISUAL:		checkfor = MOUSE_VISUAL;	break;
3150 	case SELECTMODE:	checkfor = MOUSE_VISUAL;	break;
3151 	case REPLACE:
3152 	case REPLACE+LANGMAP:
3153 	case VREPLACE:
3154 	case VREPLACE+LANGMAP:
3155 	case INSERT:
3156 	case INSERT+LANGMAP:	checkfor = MOUSE_INSERT;	break;
3157 	case ASKMORE:
3158 	case HITRETURN:		// At the more- and hit-enter prompt pass the
3159 				// mouse event for a click on or below the
3160 				// message line.
3161 				if (Y_2_ROW(y) >= msg_row)
3162 				    checkfor = MOUSE_NORMAL;
3163 				else
3164 				    checkfor = MOUSE_RETURN;
3165 				break;
3166 
3167 	    /*
3168 	     * On the command line, use the clipboard selection on all lines
3169 	     * but the command line.  But not when pasting.
3170 	     */
3171 	case CMDLINE:
3172 	case CMDLINE+LANGMAP:
3173 	    if (Y_2_ROW(y) < cmdline_row && button != MOUSE_MIDDLE)
3174 		checkfor = MOUSE_NONE;
3175 	    else
3176 		checkfor = MOUSE_COMMAND;
3177 	    break;
3178 
3179 	default:
3180 	    checkfor = MOUSE_NONE;
3181 	    break;
3182     };
3183 
3184     /*
3185      * Allow clipboard selection of text on the command line in "normal"
3186      * modes.  Don't do this when dragging the status line, or extending a
3187      * Visual selection.
3188      */
3189     if ((State == NORMAL || State == NORMAL_BUSY || (State & INSERT))
3190 	    && Y_2_ROW(y) >= topframe->fr_height + firstwin->w_winrow
3191 	    && button != MOUSE_DRAG
3192 # ifdef FEAT_MOUSESHAPE
3193 	    && !drag_status_line
3194 	    && !drag_sep_line
3195 # endif
3196 	    )
3197 	checkfor = MOUSE_NONE;
3198 
3199     /*
3200      * Use modeless selection when holding CTRL and SHIFT pressed.
3201      */
3202     if ((modifiers & MOUSE_CTRL) && (modifiers & MOUSE_SHIFT))
3203 	checkfor = MOUSE_NONEF;
3204 
3205     /*
3206      * In Ex mode, always use modeless selection.
3207      */
3208     if (exmode_active)
3209 	checkfor = MOUSE_NONE;
3210 
3211     /*
3212      * If the mouse settings say to not use the mouse, use the modeless
3213      * selection.  But if Visual is active, assume that only the Visual area
3214      * will be selected.
3215      * Exception: On the command line, both the selection is used and a mouse
3216      * key is send.
3217      */
3218     if (!mouse_has(checkfor) || checkfor == MOUSE_COMMAND)
3219     {
3220 	// Don't do modeless selection in Visual mode.
3221 	if (checkfor != MOUSE_NONEF && VIsual_active && (State & NORMAL))
3222 	    return;
3223 
3224 	/*
3225 	 * When 'mousemodel' is "popup", shift-left is translated to right.
3226 	 * But not when also using Ctrl.
3227 	 */
3228 	if (mouse_model_popup() && button == MOUSE_LEFT
3229 		&& (modifiers & MOUSE_SHIFT) && !(modifiers & MOUSE_CTRL))
3230 	{
3231 	    button = MOUSE_RIGHT;
3232 	    modifiers &= ~ MOUSE_SHIFT;
3233 	}
3234 
3235 	// If the selection is done, allow the right button to extend it.
3236 	// If the selection is cleared, allow the right button to start it
3237 	// from the cursor position.
3238 	if (button == MOUSE_RIGHT)
3239 	{
3240 	    if (clip_star.state == SELECT_CLEARED)
3241 	    {
3242 		if (State & CMDLINE)
3243 		{
3244 		    col = msg_col;
3245 		    row = msg_row;
3246 		}
3247 		else
3248 		{
3249 		    col = curwin->w_wcol;
3250 		    row = curwin->w_wrow + W_WINROW(curwin);
3251 		}
3252 		clip_start_selection(col, row, FALSE);
3253 	    }
3254 	    clip_process_selection(button, X_2_COL(x), Y_2_ROW(y),
3255 							      repeated_click);
3256 	    did_clip = TRUE;
3257 	}
3258 	// Allow the left button to start the selection
3259 	else if (button == MOUSE_LEFT)
3260 	{
3261 	    clip_start_selection(X_2_COL(x), Y_2_ROW(y), repeated_click);
3262 	    did_clip = TRUE;
3263 	}
3264 
3265 	// Always allow pasting
3266 	if (button != MOUSE_MIDDLE)
3267 	{
3268 	    if (!mouse_has(checkfor) || button == MOUSE_RELEASE)
3269 		return;
3270 	    if (checkfor != MOUSE_COMMAND)
3271 		button = MOUSE_LEFT;
3272 	}
3273 	repeated_click = FALSE;
3274     }
3275 
3276     if (clip_star.state != SELECT_CLEARED && !did_clip)
3277 	clip_clear_selection(&clip_star);
3278 #endif
3279 
3280     // Don't put events in the input queue now.
3281     if (hold_gui_events)
3282 	return;
3283 
3284     row = gui_xy2colrow(x, y, &col);
3285 
3286     /*
3287      * If we are dragging and the mouse hasn't moved far enough to be on a
3288      * different character, then don't send an event to vim.
3289      */
3290     if (button == MOUSE_DRAG)
3291     {
3292 	if (row == prev_row && col == prev_col)
3293 	    return;
3294 	// Dragging above the window, set "row" to -1 to cause a scroll.
3295 	if (y < 0)
3296 	    row = -1;
3297     }
3298 
3299     /*
3300      * If topline has changed (window scrolled) since the last click, reset
3301      * repeated_click, because we don't want starting Visual mode when
3302      * clicking on a different character in the text.
3303      */
3304     if (curwin->w_topline != gui_prev_topline
3305 #ifdef FEAT_DIFF
3306 	    || curwin->w_topfill != gui_prev_topfill
3307 #endif
3308 	    )
3309 	repeated_click = FALSE;
3310 
3311     string[0] = CSI;	// this sequence is recognized by check_termcode()
3312     string[1] = KS_MOUSE;
3313     string[2] = KE_FILLER;
3314     if (button != MOUSE_DRAG && button != MOUSE_RELEASE)
3315     {
3316 	if (repeated_click)
3317 	{
3318 	    /*
3319 	     * Handle multiple clicks.	They only count if the mouse is still
3320 	     * pointing at the same character.
3321 	     */
3322 	    if (button != prev_button || row != prev_row || col != prev_col)
3323 		num_clicks = 1;
3324 	    else if (++num_clicks > 4)
3325 		num_clicks = 1;
3326 	}
3327 	else
3328 	    num_clicks = 1;
3329 	prev_button = button;
3330 	gui_prev_topline = curwin->w_topline;
3331 #ifdef FEAT_DIFF
3332 	gui_prev_topfill = curwin->w_topfill;
3333 #endif
3334 
3335 	string[3] = (char_u)(button | 0x20);
3336 	SET_NUM_MOUSE_CLICKS(string[3], num_clicks);
3337     }
3338     else
3339 	string[3] = (char_u)button;
3340 
3341     string[3] |= modifiers;
3342     fill_mouse_coord(string + 4, col, row);
3343     add_to_input_buf(string, 8);
3344 
3345     if (row < 0)
3346 	prev_row = 0;
3347     else
3348 	prev_row = row;
3349     prev_col = col;
3350 
3351     /*
3352      * We need to make sure this is cleared since Athena doesn't tell us when
3353      * he is done dragging.  Neither does GTK+ 2 -- at least for now.
3354      */
3355 #if defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_GTK)
3356     gui.dragged_sb = SBAR_NONE;
3357 #endif
3358 }
3359 
3360 /*
3361  * Convert x and y coordinate to column and row in text window.
3362  * Corrects for multi-byte character.
3363  * returns column in "*colp" and row as return value;
3364  */
3365     static int
3366 gui_xy2colrow(int x, int y, int *colp)
3367 {
3368     int		col = check_col(X_2_COL(x));
3369     int		row = check_row(Y_2_ROW(y));
3370 
3371     *colp = mb_fix_col(col, row);
3372     return row;
3373 }
3374 
3375 #if defined(FEAT_MENU) || defined(PROTO)
3376 /*
3377  * Callback function for when a menu entry has been selected.
3378  */
3379     void
3380 gui_menu_cb(vimmenu_T *menu)
3381 {
3382     char_u  bytes[sizeof(long_u)];
3383 
3384     // Don't put events in the input queue now.
3385     if (hold_gui_events)
3386 	return;
3387 
3388     bytes[0] = CSI;
3389     bytes[1] = KS_MENU;
3390     bytes[2] = KE_FILLER;
3391     add_to_input_buf(bytes, 3);
3392     add_long_to_buf((long_u)menu, bytes);
3393     add_to_input_buf_csi(bytes, sizeof(long_u));
3394 }
3395 #endif
3396 
3397 static int	prev_which_scrollbars[3];
3398 
3399 /*
3400  * Set which components are present.
3401  * If "oldval" is not NULL, "oldval" is the previous value, the new value is
3402  * in p_go.
3403  */
3404     void
3405 gui_init_which_components(char_u *oldval UNUSED)
3406 {
3407 #ifdef FEAT_GUI_DARKTHEME
3408     static int	prev_dark_theme = -1;
3409     int		using_dark_theme = FALSE;
3410 #endif
3411 #ifdef FEAT_MENU
3412     static int	prev_menu_is_active = -1;
3413 #endif
3414 #ifdef FEAT_TOOLBAR
3415     static int	prev_toolbar = -1;
3416     int		using_toolbar = FALSE;
3417 #endif
3418 #ifdef FEAT_GUI_TABLINE
3419     int		using_tabline;
3420 #endif
3421 #ifdef FEAT_FOOTER
3422     static int	prev_footer = -1;
3423     int		using_footer = FALSE;
3424 #endif
3425 #if defined(FEAT_MENU)
3426     static int	prev_tearoff = -1;
3427     int		using_tearoff = FALSE;
3428 #endif
3429 
3430     char_u	*p;
3431     int		i;
3432 #ifdef FEAT_MENU
3433     int		grey_old, grey_new;
3434     char_u	*temp;
3435 #endif
3436     win_T	*wp;
3437     int		need_set_size;
3438     int		fix_size;
3439 
3440 #ifdef FEAT_MENU
3441     if (oldval != NULL && gui.in_use)
3442     {
3443 	/*
3444 	 * Check if the menus go from grey to non-grey or vice versa.
3445 	 */
3446 	grey_old = (vim_strchr(oldval, GO_GREY) != NULL);
3447 	grey_new = (vim_strchr(p_go, GO_GREY) != NULL);
3448 	if (grey_old != grey_new)
3449 	{
3450 	    temp = p_go;
3451 	    p_go = oldval;
3452 	    gui_update_menus(MENU_ALL_MODES);
3453 	    p_go = temp;
3454 	}
3455     }
3456     gui.menu_is_active = FALSE;
3457 #endif
3458 
3459     for (i = 0; i < 3; i++)
3460 	gui.which_scrollbars[i] = FALSE;
3461     for (p = p_go; *p; p++)
3462 	switch (*p)
3463 	{
3464 	    case GO_LEFT:
3465 		gui.which_scrollbars[SBAR_LEFT] = TRUE;
3466 		break;
3467 	    case GO_RIGHT:
3468 		gui.which_scrollbars[SBAR_RIGHT] = TRUE;
3469 		break;
3470 	    case GO_VLEFT:
3471 		if (win_hasvertsplit())
3472 		    gui.which_scrollbars[SBAR_LEFT] = TRUE;
3473 		break;
3474 	    case GO_VRIGHT:
3475 		if (win_hasvertsplit())
3476 		    gui.which_scrollbars[SBAR_RIGHT] = TRUE;
3477 		break;
3478 	    case GO_BOT:
3479 		gui.which_scrollbars[SBAR_BOTTOM] = TRUE;
3480 		break;
3481 #ifdef FEAT_GUI_DARKTHEME
3482 	    case GO_DARKTHEME:
3483 		using_dark_theme = TRUE;
3484 		break;
3485 #endif
3486 #ifdef FEAT_MENU
3487 	    case GO_MENUS:
3488 		gui.menu_is_active = TRUE;
3489 		break;
3490 #endif
3491 	    case GO_GREY:
3492 		// make menu's have grey items, ignored here
3493 		break;
3494 #ifdef FEAT_TOOLBAR
3495 	    case GO_TOOLBAR:
3496 		using_toolbar = TRUE;
3497 		break;
3498 #endif
3499 #ifdef FEAT_FOOTER
3500 	    case GO_FOOTER:
3501 		using_footer = TRUE;
3502 		break;
3503 #endif
3504 	    case GO_TEAROFF:
3505 #if defined(FEAT_MENU)
3506 		using_tearoff = TRUE;
3507 #endif
3508 		break;
3509 	    default:
3510 		// Ignore options that are not supported
3511 		break;
3512 	}
3513 
3514     if (gui.in_use)
3515     {
3516 	need_set_size = 0;
3517 	fix_size = FALSE;
3518 
3519 #ifdef FEAT_GUI_DARKTHEME
3520 	if (using_dark_theme != prev_dark_theme)
3521 	{
3522 	    gui_mch_set_dark_theme(using_dark_theme);
3523 	    prev_dark_theme = using_dark_theme;
3524 	}
3525 #endif
3526 
3527 #ifdef FEAT_GUI_TABLINE
3528 	// Update the GUI tab line, it may appear or disappear.  This may
3529 	// cause the non-GUI tab line to disappear or appear.
3530 	using_tabline = gui_has_tabline();
3531 	if (!gui_mch_showing_tabline() != !using_tabline)
3532 	{
3533 	    // We don't want a resize event change "Rows" here, save and
3534 	    // restore it.  Resizing is handled below.
3535 	    i = Rows;
3536 	    gui_update_tabline();
3537 	    Rows = i;
3538 	    need_set_size |= RESIZE_VERT;
3539 	    if (using_tabline)
3540 		fix_size = TRUE;
3541 	    if (!gui_use_tabline())
3542 		redraw_tabline = TRUE;    // may draw non-GUI tab line
3543 	}
3544 #endif
3545 
3546 	for (i = 0; i < 3; i++)
3547 	{
3548 	    // The scrollbar needs to be updated when it is shown/unshown and
3549 	    // when switching tab pages.  But the size only changes when it's
3550 	    // shown/unshown.  Thus we need two places to remember whether a
3551 	    // scrollbar is there or not.
3552 	    if (gui.which_scrollbars[i] != prev_which_scrollbars[i]
3553 		    || gui.which_scrollbars[i]
3554 					!= curtab->tp_prev_which_scrollbars[i])
3555 	    {
3556 		if (i == SBAR_BOTTOM)
3557 		    gui_mch_enable_scrollbar(&gui.bottom_sbar,
3558 						     gui.which_scrollbars[i]);
3559 		else
3560 		{
3561 		    FOR_ALL_WINDOWS(wp)
3562 			gui_do_scrollbar(wp, i, gui.which_scrollbars[i]);
3563 		}
3564 		if (gui.which_scrollbars[i] != prev_which_scrollbars[i])
3565 		{
3566 		    if (i == SBAR_BOTTOM)
3567 			need_set_size |= RESIZE_VERT;
3568 		    else
3569 			need_set_size |= RESIZE_HOR;
3570 		    if (gui.which_scrollbars[i])
3571 			fix_size = TRUE;
3572 		}
3573 	    }
3574 	    curtab->tp_prev_which_scrollbars[i] = gui.which_scrollbars[i];
3575 	    prev_which_scrollbars[i] = gui.which_scrollbars[i];
3576 	}
3577 
3578 #ifdef FEAT_MENU
3579 	if (gui.menu_is_active != prev_menu_is_active)
3580 	{
3581 	    // We don't want a resize event change "Rows" here, save and
3582 	    // restore it.  Resizing is handled below.
3583 	    i = Rows;
3584 	    gui_mch_enable_menu(gui.menu_is_active);
3585 	    Rows = i;
3586 	    prev_menu_is_active = gui.menu_is_active;
3587 	    need_set_size |= RESIZE_VERT;
3588 	    if (gui.menu_is_active)
3589 		fix_size = TRUE;
3590 	}
3591 #endif
3592 
3593 #ifdef FEAT_TOOLBAR
3594 	if (using_toolbar != prev_toolbar)
3595 	{
3596 	    gui_mch_show_toolbar(using_toolbar);
3597 	    prev_toolbar = using_toolbar;
3598 	    need_set_size |= RESIZE_VERT;
3599 	    if (using_toolbar)
3600 		fix_size = TRUE;
3601 	}
3602 #endif
3603 #ifdef FEAT_FOOTER
3604 	if (using_footer != prev_footer)
3605 	{
3606 	    gui_mch_enable_footer(using_footer);
3607 	    prev_footer = using_footer;
3608 	    need_set_size |= RESIZE_VERT;
3609 	    if (using_footer)
3610 		fix_size = TRUE;
3611 	}
3612 #endif
3613 #if defined(FEAT_MENU) && !(defined(MSWIN) && !defined(FEAT_TEAROFF))
3614 	if (using_tearoff != prev_tearoff)
3615 	{
3616 	    gui_mch_toggle_tearoffs(using_tearoff);
3617 	    prev_tearoff = using_tearoff;
3618 	}
3619 #endif
3620 	if (need_set_size != 0)
3621 	{
3622 #ifdef FEAT_GUI_GTK
3623 	    long    prev_Columns = Columns;
3624 	    long    prev_Rows = Rows;
3625 #endif
3626 	    // Adjust the size of the window to make the text area keep the
3627 	    // same size and to avoid that part of our window is off-screen
3628 	    // and a scrollbar can't be used, for example.
3629 	    gui_set_shellsize(FALSE, fix_size, need_set_size);
3630 
3631 #ifdef FEAT_GUI_GTK
3632 	    // GTK has the annoying habit of sending us resize events when
3633 	    // changing the window size ourselves.  This mostly happens when
3634 	    // waiting for a character to arrive, quite unpredictably, and may
3635 	    // change Columns and Rows when we don't want it.  Wait for a
3636 	    // character here to avoid this effect.
3637 	    // If you remove this, please test this command for resizing
3638 	    // effects (with optional left scrollbar): ":vsp|q|vsp|q|vsp|q".
3639 	    // Don't do this while starting up though.
3640 	    // Don't change Rows when adding menu/toolbar/tabline.
3641 	    // Don't change Columns when adding vertical toolbar.
3642 	    if (!gui.starting && need_set_size != (RESIZE_VERT | RESIZE_HOR))
3643 		(void)char_avail();
3644 	    if ((need_set_size & RESIZE_VERT) == 0)
3645 		Rows = prev_Rows;
3646 	    if ((need_set_size & RESIZE_HOR) == 0)
3647 		Columns = prev_Columns;
3648 #endif
3649 	}
3650 	// When the console tabline appears or disappears the window positions
3651 	// change.
3652 	if (firstwin->w_winrow != tabline_height())
3653 	    shell_new_rows();	// recompute window positions and heights
3654     }
3655 }
3656 
3657 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
3658 /*
3659  * Return TRUE if the GUI is taking care of the tabline.
3660  * It may still be hidden if 'showtabline' is zero.
3661  */
3662     int
3663 gui_use_tabline(void)
3664 {
3665     return gui.in_use && vim_strchr(p_go, GO_TABLINE) != NULL;
3666 }
3667 
3668 /*
3669  * Return TRUE if the GUI is showing the tabline.
3670  * This uses 'showtabline'.
3671  */
3672     static int
3673 gui_has_tabline(void)
3674 {
3675     if (!gui_use_tabline()
3676 	    || p_stal == 0
3677 	    || (p_stal == 1 && first_tabpage->tp_next == NULL))
3678 	return FALSE;
3679     return TRUE;
3680 }
3681 
3682 /*
3683  * Update the tabline.
3684  * This may display/undisplay the tabline and update the labels.
3685  */
3686     void
3687 gui_update_tabline(void)
3688 {
3689     int	    showit = gui_has_tabline();
3690     int	    shown = gui_mch_showing_tabline();
3691 
3692     if (!gui.starting && starting == 0)
3693     {
3694 	// Updating the tabline uses direct GUI commands, flush
3695 	// outstanding instructions first. (esp. clear screen)
3696 	out_flush();
3697 
3698 	if (!showit != !shown)
3699 	    gui_mch_show_tabline(showit);
3700 	if (showit != 0)
3701 	    gui_mch_update_tabline();
3702 
3703 	// When the tabs change from hidden to shown or from shown to
3704 	// hidden the size of the text area should remain the same.
3705 	if (!showit != !shown)
3706 	    gui_set_shellsize(FALSE, showit, RESIZE_VERT);
3707     }
3708 }
3709 
3710 /*
3711  * Get the label or tooltip for tab page "tp" into NameBuff[].
3712  */
3713     void
3714 get_tabline_label(
3715     tabpage_T	*tp,
3716     int		tooltip)	// TRUE: get tooltip
3717 {
3718     int		modified = FALSE;
3719     char_u	buf[40];
3720     int		wincount;
3721     win_T	*wp;
3722     char_u	**opt;
3723 
3724     // Use 'guitablabel' or 'guitabtooltip' if it's set.
3725     opt = (tooltip ? &p_gtt : &p_gtl);
3726     if (**opt != NUL)
3727     {
3728 	int	use_sandbox = FALSE;
3729 	int	called_emsg_before = called_emsg;
3730 	char_u	res[MAXPATHL];
3731 	tabpage_T *save_curtab;
3732 	char_u	*opt_name = (char_u *)(tooltip ? "guitabtooltip"
3733 							     : "guitablabel");
3734 
3735 	printer_page_num = tabpage_index(tp);
3736 # ifdef FEAT_EVAL
3737 	set_vim_var_nr(VV_LNUM, printer_page_num);
3738 	use_sandbox = was_set_insecurely(opt_name, 0);
3739 # endif
3740 	// It's almost as going to the tabpage, but without autocommands.
3741 	curtab->tp_firstwin = firstwin;
3742 	curtab->tp_lastwin = lastwin;
3743 	curtab->tp_curwin = curwin;
3744 	save_curtab = curtab;
3745 	curtab = tp;
3746 	topframe = curtab->tp_topframe;
3747 	firstwin = curtab->tp_firstwin;
3748 	lastwin = curtab->tp_lastwin;
3749 	curwin = curtab->tp_curwin;
3750 	curbuf = curwin->w_buffer;
3751 
3752 	// Can't use NameBuff directly, build_stl_str_hl() uses it.
3753 	build_stl_str_hl(curwin, res, MAXPATHL, *opt, use_sandbox,
3754 						 0, (int)Columns, NULL, NULL);
3755 	STRCPY(NameBuff, res);
3756 
3757 	// Back to the original curtab.
3758 	curtab = save_curtab;
3759 	topframe = curtab->tp_topframe;
3760 	firstwin = curtab->tp_firstwin;
3761 	lastwin = curtab->tp_lastwin;
3762 	curwin = curtab->tp_curwin;
3763 	curbuf = curwin->w_buffer;
3764 
3765 	if (called_emsg > called_emsg_before)
3766 	    set_string_option_direct(opt_name, -1,
3767 					   (char_u *)"", OPT_FREE, SID_ERROR);
3768     }
3769 
3770     // If 'guitablabel'/'guitabtooltip' is not set or the result is empty then
3771     // use a default label.
3772     if (**opt == NUL || *NameBuff == NUL)
3773     {
3774 	// Get the buffer name into NameBuff[] and shorten it.
3775 	get_trans_bufname(tp == curtab ? curbuf : tp->tp_curwin->w_buffer);
3776 	if (!tooltip)
3777 	    shorten_dir(NameBuff);
3778 
3779 	wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
3780 	for (wincount = 0; wp != NULL; wp = wp->w_next, ++wincount)
3781 	    if (bufIsChanged(wp->w_buffer))
3782 		modified = TRUE;
3783 	if (modified || wincount > 1)
3784 	{
3785 	    if (wincount > 1)
3786 		vim_snprintf((char *)buf, sizeof(buf), "%d", wincount);
3787 	    else
3788 		buf[0] = NUL;
3789 	    if (modified)
3790 		STRCAT(buf, "+");
3791 	    STRCAT(buf, " ");
3792 	    STRMOVE(NameBuff + STRLEN(buf), NameBuff);
3793 	    mch_memmove(NameBuff, buf, STRLEN(buf));
3794 	}
3795     }
3796 }
3797 
3798 /*
3799  * Send the event for clicking to select tab page "nr".
3800  * Returns TRUE if it was done, FALSE when skipped because we are already at
3801  * that tab page or the cmdline window is open.
3802  */
3803     int
3804 send_tabline_event(int nr)
3805 {
3806     char_u string[3];
3807 
3808     if (nr == tabpage_index(curtab))
3809 	return FALSE;
3810 
3811     // Don't put events in the input queue now.
3812     if (hold_gui_events
3813 # ifdef FEAT_CMDWIN
3814 	    || cmdwin_type != 0
3815 # endif
3816 	    )
3817     {
3818 	// Set it back to the current tab page.
3819 	gui_mch_set_curtab(tabpage_index(curtab));
3820 	return FALSE;
3821     }
3822 
3823     string[0] = CSI;
3824     string[1] = KS_TABLINE;
3825     string[2] = KE_FILLER;
3826     add_to_input_buf(string, 3);
3827     string[0] = nr;
3828     add_to_input_buf_csi(string, 1);
3829     return TRUE;
3830 }
3831 
3832 /*
3833  * Send a tabline menu event
3834  */
3835     void
3836 send_tabline_menu_event(int tabidx, int event)
3837 {
3838     char_u	    string[3];
3839 
3840     // Don't put events in the input queue now.
3841     if (hold_gui_events)
3842 	return;
3843 
3844     // Cannot close the last tabpage.
3845     if (event == TABLINE_MENU_CLOSE && first_tabpage->tp_next == NULL)
3846 	return;
3847 
3848     string[0] = CSI;
3849     string[1] = KS_TABMENU;
3850     string[2] = KE_FILLER;
3851     add_to_input_buf(string, 3);
3852     string[0] = tabidx;
3853     string[1] = (char_u)(long)event;
3854     add_to_input_buf_csi(string, 2);
3855 }
3856 
3857 #endif
3858 
3859 /*
3860  * Scrollbar stuff:
3861  */
3862 
3863 /*
3864  * Remove all scrollbars.  Used before switching to another tab page.
3865  */
3866     void
3867 gui_remove_scrollbars(void)
3868 {
3869     int	    i;
3870     win_T   *wp;
3871 
3872     for (i = 0; i < 3; i++)
3873     {
3874 	if (i == SBAR_BOTTOM)
3875 	    gui_mch_enable_scrollbar(&gui.bottom_sbar, FALSE);
3876 	else
3877 	{
3878 	    FOR_ALL_WINDOWS(wp)
3879 		gui_do_scrollbar(wp, i, FALSE);
3880 	}
3881 	curtab->tp_prev_which_scrollbars[i] = -1;
3882     }
3883 }
3884 
3885     void
3886 gui_create_scrollbar(scrollbar_T *sb, int type, win_T *wp)
3887 {
3888     static int	sbar_ident = 0;
3889 
3890     sb->ident = sbar_ident++;	// No check for too big, but would it happen?
3891     sb->wp = wp;
3892     sb->type = type;
3893     sb->value = 0;
3894 #ifdef FEAT_GUI_ATHENA
3895     sb->pixval = 0;
3896 #endif
3897     sb->size = 1;
3898     sb->max = 1;
3899     sb->top = 0;
3900     sb->height = 0;
3901     sb->width = 0;
3902     sb->status_height = 0;
3903     gui_mch_create_scrollbar(sb, (wp == NULL) ? SBAR_HORIZ : SBAR_VERT);
3904 }
3905 
3906 /*
3907  * Find the scrollbar with the given index.
3908  */
3909     scrollbar_T *
3910 gui_find_scrollbar(long ident)
3911 {
3912     win_T	*wp;
3913 
3914     if (gui.bottom_sbar.ident == ident)
3915 	return &gui.bottom_sbar;
3916     FOR_ALL_WINDOWS(wp)
3917     {
3918 	if (wp->w_scrollbars[SBAR_LEFT].ident == ident)
3919 	    return &wp->w_scrollbars[SBAR_LEFT];
3920 	if (wp->w_scrollbars[SBAR_RIGHT].ident == ident)
3921 	    return &wp->w_scrollbars[SBAR_RIGHT];
3922     }
3923     return NULL;
3924 }
3925 
3926 /*
3927  * For most systems: Put a code in the input buffer for a dragged scrollbar.
3928  *
3929  * For Win32, Macintosh and GTK+ 2:
3930  * Scrollbars seem to grab focus and vim doesn't read the input queue until
3931  * you stop dragging the scrollbar.  We get here each time the scrollbar is
3932  * dragged another pixel, but as far as the rest of vim goes, it thinks
3933  * we're just hanging in the call to DispatchMessage() in
3934  * process_message().  The DispatchMessage() call that hangs was passed a
3935  * mouse button click event in the scrollbar window. -- webb.
3936  *
3937  * Solution: Do the scrolling right here.  But only when allowed.
3938  * Ignore the scrollbars while executing an external command or when there
3939  * are still characters to be processed.
3940  */
3941     void
3942 gui_drag_scrollbar(scrollbar_T *sb, long value, int still_dragging)
3943 {
3944     win_T	*wp;
3945     int		sb_num;
3946 #ifdef USE_ON_FLY_SCROLL
3947     colnr_T	old_leftcol = curwin->w_leftcol;
3948     linenr_T	old_topline = curwin->w_topline;
3949 # ifdef FEAT_DIFF
3950     int		old_topfill = curwin->w_topfill;
3951 # endif
3952 #else
3953     char_u	bytes[sizeof(long_u)];
3954     int		byte_count;
3955 #endif
3956 
3957     if (sb == NULL)
3958 	return;
3959 
3960     // Don't put events in the input queue now.
3961     if (hold_gui_events)
3962 	return;
3963 
3964 #ifdef FEAT_CMDWIN
3965     if (cmdwin_type != 0 && sb->wp != curwin)
3966 	return;
3967 #endif
3968 
3969     if (still_dragging)
3970     {
3971 	if (sb->wp == NULL)
3972 	    gui.dragged_sb = SBAR_BOTTOM;
3973 	else if (sb == &sb->wp->w_scrollbars[SBAR_LEFT])
3974 	    gui.dragged_sb = SBAR_LEFT;
3975 	else
3976 	    gui.dragged_sb = SBAR_RIGHT;
3977 	gui.dragged_wp = sb->wp;
3978     }
3979     else
3980     {
3981 	gui.dragged_sb = SBAR_NONE;
3982 #ifdef FEAT_GUI_GTK
3983 	// Keep the "dragged_wp" value until after the scrolling, for when the
3984 	// mouse button is released.  GTK2 doesn't send the button-up event.
3985 	gui.dragged_wp = NULL;
3986 #endif
3987     }
3988 
3989     // Vertical sbar info is kept in the first sbar (the left one)
3990     if (sb->wp != NULL)
3991 	sb = &sb->wp->w_scrollbars[0];
3992 
3993     /*
3994      * Check validity of value
3995      */
3996     if (value < 0)
3997 	value = 0;
3998 #ifdef SCROLL_PAST_END
3999     else if (value > sb->max)
4000 	value = sb->max;
4001 #else
4002     if (value > sb->max - sb->size + 1)
4003 	value = sb->max - sb->size + 1;
4004 #endif
4005 
4006     sb->value = value;
4007 
4008 #ifdef USE_ON_FLY_SCROLL
4009     // When not allowed to do the scrolling right now, return.
4010     // This also checked input_available(), but that causes the first click in
4011     // a scrollbar to be ignored when Vim doesn't have focus.
4012     if (dont_scroll)
4013 	return;
4014 #endif
4015     // Disallow scrolling the current window when the completion popup menu is
4016     // visible.
4017     if ((sb->wp == NULL || sb->wp == curwin) && pum_visible())
4018 	return;
4019 
4020 #ifdef FEAT_RIGHTLEFT
4021     if (sb->wp == NULL && curwin->w_p_rl)
4022     {
4023 	value = sb->max + 1 - sb->size - value;
4024 	if (value < 0)
4025 	    value = 0;
4026     }
4027 #endif
4028 
4029     if (sb->wp != NULL)		// vertical scrollbar
4030     {
4031 	sb_num = 0;
4032 	for (wp = firstwin; wp != sb->wp && wp != NULL; wp = wp->w_next)
4033 	    sb_num++;
4034 	if (wp == NULL)
4035 	    return;
4036 
4037 #ifdef USE_ON_FLY_SCROLL
4038 	current_scrollbar = sb_num;
4039 	scrollbar_value = value;
4040 	if (State & NORMAL)
4041 	{
4042 	    gui_do_scroll();
4043 	    setcursor();
4044 	}
4045 	else if (State & INSERT)
4046 	{
4047 	    ins_scroll();
4048 	    setcursor();
4049 	}
4050 	else if (State & CMDLINE)
4051 	{
4052 	    if (msg_scrolled == 0)
4053 	    {
4054 		gui_do_scroll();
4055 		redrawcmdline();
4056 	    }
4057 	}
4058 # ifdef FEAT_FOLDING
4059 	// Value may have been changed for closed fold.
4060 	sb->value = sb->wp->w_topline - 1;
4061 # endif
4062 
4063 	// When dragging one scrollbar and there is another one at the other
4064 	// side move the thumb of that one too.
4065 	if (gui.which_scrollbars[SBAR_RIGHT] && gui.which_scrollbars[SBAR_LEFT])
4066 	    gui_mch_set_scrollbar_thumb(
4067 		    &sb->wp->w_scrollbars[
4068 			    sb == &sb->wp->w_scrollbars[SBAR_RIGHT]
4069 						    ? SBAR_LEFT : SBAR_RIGHT],
4070 		    sb->value, sb->size, sb->max);
4071 
4072 #else
4073 	bytes[0] = CSI;
4074 	bytes[1] = KS_VER_SCROLLBAR;
4075 	bytes[2] = KE_FILLER;
4076 	bytes[3] = (char_u)sb_num;
4077 	byte_count = 4;
4078 #endif
4079     }
4080     else
4081     {
4082 #ifdef USE_ON_FLY_SCROLL
4083 	scrollbar_value = value;
4084 
4085 	if (State & NORMAL)
4086 	    gui_do_horiz_scroll(scrollbar_value, FALSE);
4087 	else if (State & INSERT)
4088 	    ins_horscroll();
4089 	else if (State & CMDLINE)
4090 	{
4091 	    if (msg_scrolled == 0)
4092 	    {
4093 		gui_do_horiz_scroll(scrollbar_value, FALSE);
4094 		redrawcmdline();
4095 	    }
4096 	}
4097 	if (old_leftcol != curwin->w_leftcol)
4098 	{
4099 	    updateWindow(curwin);   // update window, status and cmdline
4100 	    setcursor();
4101 	}
4102 #else
4103 	bytes[0] = CSI;
4104 	bytes[1] = KS_HOR_SCROLLBAR;
4105 	bytes[2] = KE_FILLER;
4106 	byte_count = 3;
4107 #endif
4108     }
4109 
4110 #ifdef USE_ON_FLY_SCROLL
4111     /*
4112      * synchronize other windows, as necessary according to 'scrollbind'
4113      */
4114     if (curwin->w_p_scb
4115 	    && ((sb->wp == NULL && curwin->w_leftcol != old_leftcol)
4116 		|| (sb->wp == curwin && (curwin->w_topline != old_topline
4117 # ifdef FEAT_DIFF
4118 					   || curwin->w_topfill != old_topfill
4119 # endif
4120 			))))
4121     {
4122 	do_check_scrollbind(TRUE);
4123 	// need to update the window right here
4124 	FOR_ALL_WINDOWS(wp)
4125 	    if (wp->w_redr_type > 0)
4126 		updateWindow(wp);
4127 	setcursor();
4128     }
4129     out_flush_cursor(FALSE, TRUE);
4130 #else
4131     add_to_input_buf(bytes, byte_count);
4132     add_long_to_buf((long_u)value, bytes);
4133     add_to_input_buf_csi(bytes, sizeof(long_u));
4134 #endif
4135 }
4136 
4137 /*
4138  * Scrollbar stuff:
4139  */
4140 
4141 /*
4142  * Called when something in the window layout has changed.
4143  */
4144     void
4145 gui_may_update_scrollbars(void)
4146 {
4147     if (gui.in_use && starting == 0)
4148     {
4149 	out_flush();
4150 	gui_init_which_components(NULL);
4151 	gui_update_scrollbars(TRUE);
4152     }
4153     need_mouse_correct = TRUE;
4154 }
4155 
4156     void
4157 gui_update_scrollbars(
4158     int		force)	    // Force all scrollbars to get updated
4159 {
4160     win_T	*wp;
4161     scrollbar_T	*sb;
4162     long	val, size, max;		// need 32 bits here
4163     int		which_sb;
4164     int		h, y;
4165     static win_T *prev_curwin = NULL;
4166 
4167     // Update the horizontal scrollbar
4168     gui_update_horiz_scrollbar(force);
4169 
4170 #ifndef MSWIN
4171     // Return straight away if there is neither a left nor right scrollbar.
4172     // On MS-Windows this is required anyway for scrollwheel messages.
4173     if (!gui.which_scrollbars[SBAR_LEFT] && !gui.which_scrollbars[SBAR_RIGHT])
4174 	return;
4175 #endif
4176 
4177     /*
4178      * Don't want to update a scrollbar while we're dragging it.  But if we
4179      * have both a left and right scrollbar, and we drag one of them, we still
4180      * need to update the other one.
4181      */
4182     if (!force && (gui.dragged_sb == SBAR_LEFT || gui.dragged_sb == SBAR_RIGHT)
4183 	    && gui.which_scrollbars[SBAR_LEFT]
4184 	    && gui.which_scrollbars[SBAR_RIGHT])
4185     {
4186 	/*
4187 	 * If we have two scrollbars and one of them is being dragged, just
4188 	 * copy the scrollbar position from the dragged one to the other one.
4189 	 */
4190 	which_sb = SBAR_LEFT + SBAR_RIGHT - gui.dragged_sb;
4191 	if (gui.dragged_wp != NULL)
4192 	    gui_mch_set_scrollbar_thumb(
4193 		    &gui.dragged_wp->w_scrollbars[which_sb],
4194 		    gui.dragged_wp->w_scrollbars[0].value,
4195 		    gui.dragged_wp->w_scrollbars[0].size,
4196 		    gui.dragged_wp->w_scrollbars[0].max);
4197     }
4198 
4199     // avoid that moving components around generates events
4200     ++hold_gui_events;
4201 
4202     FOR_ALL_WINDOWS(wp)
4203     {
4204 	if (wp->w_buffer == NULL)	// just in case
4205 	    continue;
4206 	// Skip a scrollbar that is being dragged.
4207 	if (!force && (gui.dragged_sb == SBAR_LEFT
4208 					     || gui.dragged_sb == SBAR_RIGHT)
4209 		&& gui.dragged_wp == wp)
4210 	    continue;
4211 
4212 #ifdef SCROLL_PAST_END
4213 	max = wp->w_buffer->b_ml.ml_line_count - 1;
4214 #else
4215 	max = wp->w_buffer->b_ml.ml_line_count + wp->w_height - 2;
4216 #endif
4217 	if (max < 0)			// empty buffer
4218 	    max = 0;
4219 	val = wp->w_topline - 1;
4220 	size = wp->w_height;
4221 #ifdef SCROLL_PAST_END
4222 	if (val > max)			// just in case
4223 	    val = max;
4224 #else
4225 	if (size > max + 1)		// just in case
4226 	    size = max + 1;
4227 	if (val > max - size + 1)
4228 	    val = max - size + 1;
4229 #endif
4230 	if (val < 0)			// minimal value is 0
4231 	    val = 0;
4232 
4233 	/*
4234 	 * Scrollbar at index 0 (the left one) contains all the information.
4235 	 * It would be the same info for left and right so we just store it for
4236 	 * one of them.
4237 	 */
4238 	sb = &wp->w_scrollbars[0];
4239 
4240 	/*
4241 	 * Note: no check for valid w_botline.	If it's not valid the
4242 	 * scrollbars will be updated later anyway.
4243 	 */
4244 	if (size < 1 || wp->w_botline - 2 > max)
4245 	{
4246 	    /*
4247 	     * This can happen during changing files.  Just don't update the
4248 	     * scrollbar for now.
4249 	     */
4250 	    sb->height = 0;	    // Force update next time
4251 	    if (gui.which_scrollbars[SBAR_LEFT])
4252 		gui_do_scrollbar(wp, SBAR_LEFT, FALSE);
4253 	    if (gui.which_scrollbars[SBAR_RIGHT])
4254 		gui_do_scrollbar(wp, SBAR_RIGHT, FALSE);
4255 	    continue;
4256 	}
4257 	if (force || sb->height != wp->w_height
4258 	    || sb->top != wp->w_winrow
4259 	    || sb->status_height != wp->w_status_height
4260 	    || sb->width != wp->w_width
4261 	    || prev_curwin != curwin)
4262 	{
4263 	    // Height, width or position of scrollbar has changed.  For
4264 	    // vertical split: curwin changed.
4265 	    sb->height = wp->w_height;
4266 	    sb->top = wp->w_winrow;
4267 	    sb->status_height = wp->w_status_height;
4268 	    sb->width = wp->w_width;
4269 
4270 	    // Calculate height and position in pixels
4271 	    h = (sb->height + sb->status_height) * gui.char_height;
4272 	    y = sb->top * gui.char_height + gui.border_offset;
4273 #if defined(FEAT_MENU) && !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_MOTIF) && !defined(FEAT_GUI_PHOTON)
4274 	    if (gui.menu_is_active)
4275 		y += gui.menu_height;
4276 #endif
4277 
4278 #if defined(FEAT_TOOLBAR) && (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_ATHENA) \
4279 	|| defined(FEAT_GUI_HAIKU))
4280 	    if (vim_strchr(p_go, GO_TOOLBAR) != NULL)
4281 # if defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_HAIKU)
4282 		y += gui.toolbar_height;
4283 # else
4284 #  ifdef FEAT_GUI_MSWIN
4285 		y += TOOLBAR_BUTTON_HEIGHT + TOOLBAR_BORDER_HEIGHT;
4286 #  endif
4287 # endif
4288 #endif
4289 
4290 #if defined(FEAT_GUI_TABLINE) && defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_HAIKU)
4291 	    if (gui_has_tabline())
4292 		y += gui.tabline_height;
4293 #endif
4294 
4295 	    if (wp->w_winrow == 0)
4296 	    {
4297 		// Height of top scrollbar includes width of top border
4298 		h += gui.border_offset;
4299 		y -= gui.border_offset;
4300 	    }
4301 	    if (gui.which_scrollbars[SBAR_LEFT])
4302 	    {
4303 		gui_mch_set_scrollbar_pos(&wp->w_scrollbars[SBAR_LEFT],
4304 					  gui.left_sbar_x, y,
4305 					  gui.scrollbar_width, h);
4306 		gui_do_scrollbar(wp, SBAR_LEFT, TRUE);
4307 	    }
4308 	    if (gui.which_scrollbars[SBAR_RIGHT])
4309 	    {
4310 		gui_mch_set_scrollbar_pos(&wp->w_scrollbars[SBAR_RIGHT],
4311 					  gui.right_sbar_x, y,
4312 					  gui.scrollbar_width, h);
4313 		gui_do_scrollbar(wp, SBAR_RIGHT, TRUE);
4314 	    }
4315 	}
4316 
4317 	// Reduce the number of calls to gui_mch_set_scrollbar_thumb() by
4318 	// checking if the thumb moved at least a pixel.  Only do this for
4319 	// Athena, most other GUIs require the update anyway to make the
4320 	// arrows work.
4321 #ifdef FEAT_GUI_ATHENA
4322 	if (max == 0)
4323 	    y = 0;
4324 	else
4325 	    y = (val * (sb->height + 2) * gui.char_height + max / 2) / max;
4326 	if (force || sb->pixval != y || sb->size != size || sb->max != max)
4327 #else
4328 	if (force || sb->value != val || sb->size != size || sb->max != max)
4329 #endif
4330 	{
4331 	    // Thumb of scrollbar has moved
4332 	    sb->value = val;
4333 #ifdef FEAT_GUI_ATHENA
4334 	    sb->pixval = y;
4335 #endif
4336 	    sb->size = size;
4337 	    sb->max = max;
4338 	    if (gui.which_scrollbars[SBAR_LEFT]
4339 		    && (gui.dragged_sb != SBAR_LEFT || gui.dragged_wp != wp))
4340 		gui_mch_set_scrollbar_thumb(&wp->w_scrollbars[SBAR_LEFT],
4341 					    val, size, max);
4342 	    if (gui.which_scrollbars[SBAR_RIGHT]
4343 		    && (gui.dragged_sb != SBAR_RIGHT || gui.dragged_wp != wp))
4344 		gui_mch_set_scrollbar_thumb(&wp->w_scrollbars[SBAR_RIGHT],
4345 					    val, size, max);
4346 	}
4347     }
4348     prev_curwin = curwin;
4349     --hold_gui_events;
4350 }
4351 
4352 /*
4353  * Enable or disable a scrollbar.
4354  * Check for scrollbars for vertically split windows which are not enabled
4355  * sometimes.
4356  */
4357     static void
4358 gui_do_scrollbar(
4359     win_T	*wp,
4360     int		which,	    // SBAR_LEFT or SBAR_RIGHT
4361     int		enable)	    // TRUE to enable scrollbar
4362 {
4363     int		midcol = curwin->w_wincol + curwin->w_width / 2;
4364     int		has_midcol = (wp->w_wincol <= midcol
4365 				     && wp->w_wincol + wp->w_width >= midcol);
4366 
4367     // Only enable scrollbars that contain the middle column of the current
4368     // window.
4369     if (gui.which_scrollbars[SBAR_RIGHT] != gui.which_scrollbars[SBAR_LEFT])
4370     {
4371 	// Scrollbars only on one side.  Don't enable scrollbars that don't
4372 	// contain the middle column of the current window.
4373 	if (!has_midcol)
4374 	    enable = FALSE;
4375     }
4376     else
4377     {
4378 	// Scrollbars on both sides.  Don't enable scrollbars that neither
4379 	// contain the middle column of the current window nor are on the far
4380 	// side.
4381 	if (midcol > Columns / 2)
4382 	{
4383 	    if (which == SBAR_LEFT ? wp->w_wincol != 0 : !has_midcol)
4384 		enable = FALSE;
4385 	}
4386 	else
4387 	{
4388 	    if (which == SBAR_RIGHT ? wp->w_wincol + wp->w_width != Columns
4389 								: !has_midcol)
4390 		enable = FALSE;
4391 	}
4392     }
4393     gui_mch_enable_scrollbar(&wp->w_scrollbars[which], enable);
4394 }
4395 
4396 /*
4397  * Scroll a window according to the values set in the globals current_scrollbar
4398  * and scrollbar_value.  Return TRUE if the cursor in the current window moved
4399  * or FALSE otherwise.
4400  */
4401     int
4402 gui_do_scroll(void)
4403 {
4404     win_T	*wp, *save_wp;
4405     int		i;
4406     long	nlines;
4407     pos_T	old_cursor;
4408     linenr_T	old_topline;
4409 #ifdef FEAT_DIFF
4410     int		old_topfill;
4411 #endif
4412 
4413     for (wp = firstwin, i = 0; i < current_scrollbar; wp = W_NEXT(wp), i++)
4414 	if (wp == NULL)
4415 	    break;
4416     if (wp == NULL)
4417 	// Couldn't find window
4418 	return FALSE;
4419 
4420     /*
4421      * Compute number of lines to scroll.  If zero, nothing to do.
4422      */
4423     nlines = (long)scrollbar_value + 1 - (long)wp->w_topline;
4424     if (nlines == 0)
4425 	return FALSE;
4426 
4427     save_wp = curwin;
4428     old_topline = wp->w_topline;
4429 #ifdef FEAT_DIFF
4430     old_topfill = wp->w_topfill;
4431 #endif
4432     old_cursor = wp->w_cursor;
4433     curwin = wp;
4434     curbuf = wp->w_buffer;
4435     if (nlines < 0)
4436 	scrolldown(-nlines, gui.dragged_wp == NULL);
4437     else
4438 	scrollup(nlines, gui.dragged_wp == NULL);
4439     // Reset dragged_wp after using it.  "dragged_sb" will have been reset for
4440     // the mouse-up event already, but we still want it to behave like when
4441     // dragging.  But not the next click in an arrow.
4442     if (gui.dragged_sb == SBAR_NONE)
4443 	gui.dragged_wp = NULL;
4444 
4445     if (old_topline != wp->w_topline
4446 #ifdef FEAT_DIFF
4447 	    || old_topfill != wp->w_topfill
4448 #endif
4449 	    )
4450     {
4451 	if (get_scrolloff_value() != 0)
4452 	{
4453 	    cursor_correct();		// fix window for 'so'
4454 	    update_topline();		// avoid up/down jump
4455 	}
4456 	if (old_cursor.lnum != wp->w_cursor.lnum)
4457 	    coladvance(wp->w_curswant);
4458 	wp->w_scbind_pos = wp->w_topline;
4459     }
4460 
4461     // Make sure wp->w_leftcol and wp->w_skipcol are correct.
4462     validate_cursor();
4463 
4464     curwin = save_wp;
4465     curbuf = save_wp->w_buffer;
4466 
4467     /*
4468      * Don't call updateWindow() when nothing has changed (it will overwrite
4469      * the status line!).
4470      */
4471     if (old_topline != wp->w_topline
4472 	    || wp->w_redr_type != 0
4473 #ifdef FEAT_DIFF
4474 	    || old_topfill != wp->w_topfill
4475 #endif
4476 	    )
4477     {
4478 	int type = VALID;
4479 
4480 	if (pum_visible())
4481 	{
4482 	    type = NOT_VALID;
4483 	    wp->w_lines_valid = 0;
4484 	}
4485 
4486 	// Don't set must_redraw here, it may cause the popup menu to
4487 	// disappear when losing focus after a scrollbar drag.
4488 	if (wp->w_redr_type < type)
4489 	    wp->w_redr_type = type;
4490 	mch_disable_flush();
4491 	updateWindow(wp);   // update window, status line, and cmdline
4492 	mch_enable_flush();
4493     }
4494 
4495     // May need to redraw the popup menu.
4496     if (pum_visible())
4497 	pum_redraw();
4498 
4499     return (wp == curwin && !EQUAL_POS(curwin->w_cursor, old_cursor));
4500 }
4501 
4502 
4503 /*
4504  * Horizontal scrollbar stuff:
4505  */
4506 
4507 /*
4508  * Return length of line "lnum" for horizontal scrolling.
4509  */
4510     static colnr_T
4511 scroll_line_len(linenr_T lnum)
4512 {
4513     char_u	*p;
4514     colnr_T	col;
4515     int		w;
4516 
4517     p = ml_get(lnum);
4518     col = 0;
4519     if (*p != NUL)
4520 	for (;;)
4521 	{
4522 	    w = chartabsize(p, col);
4523 	    MB_PTR_ADV(p);
4524 	    if (*p == NUL)		// don't count the last character
4525 		break;
4526 	    col += w;
4527 	}
4528     return col;
4529 }
4530 
4531 // Remember which line is currently the longest, so that we don't have to
4532 // search for it when scrolling horizontally.
4533 static linenr_T longest_lnum = 0;
4534 
4535 /*
4536  * Find longest visible line number.  If this is not possible (or not desired,
4537  * by setting 'h' in "guioptions") then the current line number is returned.
4538  */
4539     static linenr_T
4540 gui_find_longest_lnum(void)
4541 {
4542     linenr_T ret = 0;
4543 
4544     // Calculate maximum for horizontal scrollbar.  Check for reasonable
4545     // line numbers, topline and botline can be invalid when displaying is
4546     // postponed.
4547     if (vim_strchr(p_go, GO_HORSCROLL) == NULL
4548 	    && curwin->w_topline <= curwin->w_cursor.lnum
4549 	    && curwin->w_botline > curwin->w_cursor.lnum
4550 	    && curwin->w_botline <= curbuf->b_ml.ml_line_count + 1)
4551     {
4552 	linenr_T    lnum;
4553 	colnr_T	    n;
4554 	long	    max = 0;
4555 
4556 	// Use maximum of all visible lines.  Remember the lnum of the
4557 	// longest line, closest to the cursor line.  Used when scrolling
4558 	// below.
4559 	for (lnum = curwin->w_topline; lnum < curwin->w_botline; ++lnum)
4560 	{
4561 	    n = scroll_line_len(lnum);
4562 	    if (n > (colnr_T)max)
4563 	    {
4564 		max = n;
4565 		ret = lnum;
4566 	    }
4567 	    else if (n == (colnr_T)max
4568 		    && abs((int)(lnum - curwin->w_cursor.lnum))
4569 		       < abs((int)(ret - curwin->w_cursor.lnum)))
4570 		ret = lnum;
4571 	}
4572     }
4573     else
4574 	// Use cursor line only.
4575 	ret = curwin->w_cursor.lnum;
4576 
4577     return ret;
4578 }
4579 
4580     static void
4581 gui_update_horiz_scrollbar(int force)
4582 {
4583     long	value, size, max;	// need 32 bit ints here
4584 
4585     if (!gui.which_scrollbars[SBAR_BOTTOM])
4586 	return;
4587 
4588     if (!force && gui.dragged_sb == SBAR_BOTTOM)
4589 	return;
4590 
4591     if (!force && curwin->w_p_wrap && gui.prev_wrap)
4592 	return;
4593 
4594     /*
4595      * It is possible for the cursor to be invalid if we're in the middle of
4596      * something (like changing files).  If so, don't do anything for now.
4597      */
4598     if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
4599     {
4600 	gui.bottom_sbar.value = -1;
4601 	return;
4602     }
4603 
4604     size = curwin->w_width;
4605     if (curwin->w_p_wrap)
4606     {
4607 	value = 0;
4608 #ifdef SCROLL_PAST_END
4609 	max = 0;
4610 #else
4611 	max = curwin->w_width - 1;
4612 #endif
4613     }
4614     else
4615     {
4616 	value = curwin->w_leftcol;
4617 
4618 	longest_lnum = gui_find_longest_lnum();
4619 	max = scroll_line_len(longest_lnum);
4620 
4621 	if (virtual_active())
4622 	{
4623 	    // May move the cursor even further to the right.
4624 	    if (curwin->w_virtcol >= (colnr_T)max)
4625 		max = curwin->w_virtcol;
4626 	}
4627 
4628 #ifndef SCROLL_PAST_END
4629 	max += curwin->w_width - 1;
4630 #endif
4631 	// The line number isn't scrolled, thus there is less space when
4632 	// 'number' or 'relativenumber' is set (also for 'foldcolumn').
4633 	size -= curwin_col_off();
4634 #ifndef SCROLL_PAST_END
4635 	max -= curwin_col_off();
4636 #endif
4637     }
4638 
4639 #ifndef SCROLL_PAST_END
4640     if (value > max - size + 1)
4641 	value = max - size + 1;	    // limit the value to allowable range
4642 #endif
4643 
4644 #ifdef FEAT_RIGHTLEFT
4645     if (curwin->w_p_rl)
4646     {
4647 	value = max + 1 - size - value;
4648 	if (value < 0)
4649 	{
4650 	    size += value;
4651 	    value = 0;
4652 	}
4653     }
4654 #endif
4655     if (!force && value == gui.bottom_sbar.value && size == gui.bottom_sbar.size
4656 						&& max == gui.bottom_sbar.max)
4657 	return;
4658 
4659     gui.bottom_sbar.value = value;
4660     gui.bottom_sbar.size = size;
4661     gui.bottom_sbar.max = max;
4662     gui.prev_wrap = curwin->w_p_wrap;
4663 
4664     gui_mch_set_scrollbar_thumb(&gui.bottom_sbar, value, size, max);
4665 }
4666 
4667 /*
4668  * Do a horizontal scroll.  Return TRUE if the cursor moved, FALSE otherwise.
4669  */
4670     int
4671 gui_do_horiz_scroll(long_u leftcol, int compute_longest_lnum)
4672 {
4673     // no wrapping, no scrolling
4674     if (curwin->w_p_wrap)
4675 	return FALSE;
4676 
4677     if (curwin->w_leftcol == (colnr_T)leftcol)
4678 	return FALSE;
4679 
4680     curwin->w_leftcol = (colnr_T)leftcol;
4681 
4682     // When the line of the cursor is too short, move the cursor to the
4683     // longest visible line.
4684     if (vim_strchr(p_go, GO_HORSCROLL) == NULL
4685 	    && !virtual_active()
4686 	    && (colnr_T)leftcol > scroll_line_len(curwin->w_cursor.lnum))
4687     {
4688 	if (compute_longest_lnum)
4689 	{
4690 	    curwin->w_cursor.lnum = gui_find_longest_lnum();
4691 	    curwin->w_cursor.col = 0;
4692 	}
4693 	// Do a sanity check on "longest_lnum", just in case.
4694 	else if (longest_lnum >= curwin->w_topline
4695 		&& longest_lnum < curwin->w_botline)
4696 	{
4697 	    curwin->w_cursor.lnum = longest_lnum;
4698 	    curwin->w_cursor.col = 0;
4699 	}
4700     }
4701 
4702     return leftcol_changed();
4703 }
4704 
4705 /*
4706  * Check that none of the colors are the same as the background color
4707  */
4708     void
4709 gui_check_colors(void)
4710 {
4711     if (gui.norm_pixel == gui.back_pixel || gui.norm_pixel == INVALCOLOR)
4712     {
4713 	gui_set_bg_color((char_u *)"White");
4714 	if (gui.norm_pixel == gui.back_pixel || gui.norm_pixel == INVALCOLOR)
4715 	    gui_set_fg_color((char_u *)"Black");
4716     }
4717 }
4718 
4719     static void
4720 gui_set_fg_color(char_u *name)
4721 {
4722     gui.norm_pixel = gui_get_color(name);
4723     hl_set_fg_color_name(vim_strsave(name));
4724 }
4725 
4726     static void
4727 gui_set_bg_color(char_u *name)
4728 {
4729     gui.back_pixel = gui_get_color(name);
4730     hl_set_bg_color_name(vim_strsave(name));
4731 }
4732 
4733 /*
4734  * Allocate a color by name.
4735  * Returns INVALCOLOR and gives an error message when failed.
4736  */
4737     guicolor_T
4738 gui_get_color(char_u *name)
4739 {
4740     guicolor_T	t;
4741 
4742     if (*name == NUL)
4743 	return INVALCOLOR;
4744     t = gui_mch_get_color(name);
4745 
4746     if (t == INVALCOLOR
4747 #if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
4748 	    && gui.in_use
4749 #endif
4750 	    )
4751 	semsg(_(e_alloc_color), name);
4752     return t;
4753 }
4754 
4755 /*
4756  * Return the grey value of a color (range 0-255).
4757  */
4758     int
4759 gui_get_lightness(guicolor_T pixel)
4760 {
4761     long_u	rgb = (long_u)gui_mch_get_rgb(pixel);
4762 
4763     return  (int)(  (((rgb >> 16) & 0xff) * 299)
4764 		   + (((rgb >> 8) & 0xff) * 587)
4765 		   +  ((rgb	  & 0xff) * 114)) / 1000;
4766 }
4767 
4768     char_u *
4769 gui_bg_default(void)
4770 {
4771     if (gui_get_lightness(gui.back_pixel) < 127)
4772 	return (char_u *)"dark";
4773     return (char_u *)"light";
4774 }
4775 
4776 /*
4777  * Option initializations that can only be done after opening the GUI window.
4778  */
4779     void
4780 init_gui_options(void)
4781 {
4782     // Set the 'background' option according to the lightness of the
4783     // background color, unless the user has set it already.
4784     if (!option_was_set((char_u *)"bg") && STRCMP(p_bg, gui_bg_default()) != 0)
4785     {
4786 	set_option_value((char_u *)"bg", 0L, gui_bg_default(), 0);
4787 	highlight_changed();
4788     }
4789 }
4790 
4791 #if defined(FEAT_GUI_X11) || defined(PROTO)
4792     void
4793 gui_new_scrollbar_colors(void)
4794 {
4795     win_T	*wp;
4796 
4797     // Nothing to do if GUI hasn't started yet.
4798     if (!gui.in_use)
4799 	return;
4800 
4801     FOR_ALL_WINDOWS(wp)
4802     {
4803 	gui_mch_set_scrollbar_colors(&(wp->w_scrollbars[SBAR_LEFT]));
4804 	gui_mch_set_scrollbar_colors(&(wp->w_scrollbars[SBAR_RIGHT]));
4805     }
4806     gui_mch_set_scrollbar_colors(&gui.bottom_sbar);
4807 }
4808 #endif
4809 
4810 /*
4811  * Call this when focus has changed.
4812  */
4813     void
4814 gui_focus_change(int in_focus)
4815 {
4816 /*
4817  * Skip this code to avoid drawing the cursor when debugging and switching
4818  * between the debugger window and gvim.
4819  */
4820 #if 1
4821     gui.in_focus = in_focus;
4822     out_flush_cursor(TRUE, FALSE);
4823 
4824 # ifdef FEAT_XIM
4825     xim_set_focus(in_focus);
4826 # endif
4827 
4828     // Put events in the input queue only when allowed.
4829     // ui_focus_change() isn't called directly, because it invokes
4830     // autocommands and that must not happen asynchronously.
4831     if (!hold_gui_events)
4832     {
4833 	char_u  bytes[3];
4834 
4835 	bytes[0] = CSI;
4836 	bytes[1] = KS_EXTRA;
4837 	bytes[2] = in_focus ? (int)KE_FOCUSGAINED : (int)KE_FOCUSLOST;
4838 	add_to_input_buf(bytes, 3);
4839     }
4840 #endif
4841 }
4842 
4843 /*
4844  * When mouse moved: apply 'mousefocus'.
4845  * Also updates the mouse pointer shape.
4846  */
4847     static void
4848 gui_mouse_focus(int x, int y)
4849 {
4850     win_T	*wp;
4851     char_u	st[8];
4852 
4853 #ifdef FEAT_MOUSESHAPE
4854     // Get window pointer, and update mouse shape as well.
4855     wp = xy2win(x, y, IGNORE_POPUP);
4856 #endif
4857 
4858     // Only handle this when 'mousefocus' set and ...
4859     if (p_mousef
4860 	    && !hold_gui_events		// not holding events
4861 	    && (State & (NORMAL|INSERT))// Normal/Visual/Insert mode
4862 	    && State != HITRETURN	// but not hit-return prompt
4863 	    && msg_scrolled == 0	// no scrolled message
4864 	    && !need_mouse_correct	// not moving the pointer
4865 	    && gui.in_focus)		// gvim in focus
4866     {
4867 	// Don't move the mouse when it's left or right of the Vim window
4868 	if (x < 0 || x > Columns * gui.char_width)
4869 	    return;
4870 #ifndef FEAT_MOUSESHAPE
4871 	wp = xy2win(x, y, IGNORE_POPUP);
4872 #endif
4873 	if (wp == curwin || wp == NULL)
4874 	    return;	// still in the same old window, or none at all
4875 
4876 	// Ignore position in the tab pages line.
4877 	if (Y_2_ROW(y) < tabline_height())
4878 	    return;
4879 
4880 	/*
4881 	 * format a mouse click on status line input
4882 	 * ala gui_send_mouse_event(0, x, y, 0, 0);
4883 	 * Trick: Use a column number -1, so that get_pseudo_mouse_code() will
4884 	 * generate a K_LEFTMOUSE_NM key code.
4885 	 */
4886 	if (finish_op)
4887 	{
4888 	    // abort the current operator first
4889 	    st[0] = ESC;
4890 	    add_to_input_buf(st, 1);
4891 	}
4892 	st[0] = CSI;
4893 	st[1] = KS_MOUSE;
4894 	st[2] = KE_FILLER;
4895 	st[3] = (char_u)MOUSE_LEFT;
4896 	fill_mouse_coord(st + 4,
4897 		wp->w_wincol == 0 ? -1 : wp->w_wincol + MOUSE_COLOFF,
4898 		wp->w_height + W_WINROW(wp));
4899 
4900 	add_to_input_buf(st, 8);
4901 	st[3] = (char_u)MOUSE_RELEASE;
4902 	add_to_input_buf(st, 8);
4903 #ifdef FEAT_GUI_GTK
4904 	// Need to wake up the main loop
4905 	if (gtk_main_level() > 0)
4906 	    gtk_main_quit();
4907 #endif
4908     }
4909 }
4910 
4911 /*
4912  * Called when the mouse moved (but not when dragging).
4913  */
4914     void
4915 gui_mouse_moved(int x, int y)
4916 {
4917     // Ignore this while still starting up.
4918     if (!gui.in_use || gui.starting)
4919 	return;
4920 
4921     // apply 'mousefocus' and pointer shape
4922     gui_mouse_focus(x, y);
4923 
4924 #ifdef FEAT_PROP_POPUP
4925     if (popup_visible)
4926 	// Generate a mouse-moved event, so that the popup can perhaps be
4927 	// closed, just like in the terminal.
4928 	gui_send_mouse_event(MOUSE_DRAG, x, y, FALSE, 0);
4929 #endif
4930 }
4931 
4932 /*
4933  * Get the window where the mouse pointer is on.
4934  * Returns NULL if not found.
4935  */
4936     win_T *
4937 gui_mouse_window(mouse_find_T popup)
4938 {
4939     int		x, y;
4940 
4941     if (!(gui.in_use && (p_mousef || popup == FIND_POPUP)))
4942 	return NULL;
4943     gui_mch_getmouse(&x, &y);
4944 
4945     // Only use the mouse when it's on the Vim window
4946     if (x >= 0 && x <= Columns * gui.char_width
4947 	    && y >= 0 && Y_2_ROW(y) >= tabline_height())
4948 	return xy2win(x, y, popup);
4949     return NULL;
4950 }
4951 
4952 /*
4953  * Called when mouse should be moved to window with focus.
4954  */
4955     void
4956 gui_mouse_correct(void)
4957 {
4958     win_T	*wp = NULL;
4959 
4960     need_mouse_correct = FALSE;
4961 
4962     wp = gui_mouse_window(IGNORE_POPUP);
4963     if (wp != curwin && wp != NULL)	// If in other than current window
4964     {
4965 	validate_cline_row();
4966 	gui_mch_setmouse((int)W_ENDCOL(curwin) * gui.char_width - 3,
4967 		(W_WINROW(curwin) + curwin->w_wrow) * gui.char_height
4968 						     + (gui.char_height) / 2);
4969     }
4970 }
4971 
4972 /*
4973  * Find window where the mouse pointer "x" / "y" coordinate is in.
4974  * As a side effect update the shape of the mouse pointer.
4975  */
4976     static win_T *
4977 xy2win(int x, int y, mouse_find_T popup)
4978 {
4979     int		row;
4980     int		col;
4981     win_T	*wp;
4982 
4983     row = Y_2_ROW(y);
4984     col = X_2_COL(x);
4985     if (row < 0 || col < 0)		// before first window
4986 	return NULL;
4987     wp = mouse_find_win(&row, &col, popup);
4988     if (wp == NULL)
4989 	return NULL;
4990 #ifdef FEAT_MOUSESHAPE
4991     if (State == HITRETURN || State == ASKMORE)
4992     {
4993 	if (Y_2_ROW(y) >= msg_row)
4994 	    update_mouseshape(SHAPE_IDX_MOREL);
4995 	else
4996 	    update_mouseshape(SHAPE_IDX_MORE);
4997     }
4998     else if (row > wp->w_height)	// below status line
4999 	update_mouseshape(SHAPE_IDX_CLINE);
5000     else if (!(State & CMDLINE) && wp->w_vsep_width > 0 && col == wp->w_width
5001 	    && (row != wp->w_height || !stl_connected(wp)) && msg_scrolled == 0)
5002 	update_mouseshape(SHAPE_IDX_VSEP);
5003     else if (!(State & CMDLINE) && wp->w_status_height > 0
5004 				  && row == wp->w_height && msg_scrolled == 0)
5005 	update_mouseshape(SHAPE_IDX_STATUS);
5006     else
5007 	update_mouseshape(-2);
5008 #endif
5009     return wp;
5010 }
5011 
5012 /*
5013  * ":gui" and ":gvim": Change from the terminal version to the GUI version.
5014  * File names may be given to redefine the args list.
5015  */
5016     void
5017 ex_gui(exarg_T *eap)
5018 {
5019     char_u	*arg = eap->arg;
5020 
5021     /*
5022      * Check for "-f" argument: foreground, don't fork.
5023      * Also don't fork when started with "gvim -f".
5024      * Do fork when using "gui -b".
5025      */
5026     if (arg[0] == '-'
5027 	    && (arg[1] == 'f' || arg[1] == 'b')
5028 	    && (arg[2] == NUL || VIM_ISWHITE(arg[2])))
5029     {
5030 	gui.dofork = (arg[1] == 'b');
5031 	eap->arg = skipwhite(eap->arg + 2);
5032     }
5033     if (!gui.in_use)
5034     {
5035 #if defined(VIMDLL) && !defined(EXPERIMENTAL_GUI_CMD)
5036 	if (!gui.starting)
5037 	{
5038 	    emsg(_(e_nogvim));
5039 	    return;
5040 	}
5041 #endif
5042 	// Clear the command.  Needed for when forking+exiting, to avoid part
5043 	// of the argument ending up after the shell prompt.
5044 	msg_clr_eos_force();
5045 #ifdef GUI_MAY_SPAWN
5046 	if (!ends_excmd2(eap->cmd, eap->arg))
5047 	    gui_start(eap->arg);
5048 	else
5049 #endif
5050 	    gui_start(NULL);
5051 #ifdef FEAT_JOB_CHANNEL
5052 	channel_gui_register_all();
5053 #endif
5054     }
5055     if (!ends_excmd2(eap->cmd, eap->arg))
5056 	ex_next(eap);
5057 }
5058 
5059 #if ((defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK) \
5060 	    || defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_PHOTON) \
5061 	    || defined(FEAT_GUI_HAIKU)) \
5062 	    && defined(FEAT_TOOLBAR)) || defined(PROTO)
5063 /*
5064  * This is shared between Athena, Haiku, Motif, and GTK.
5065  */
5066 
5067 /*
5068  * Callback function for do_in_runtimepath().
5069  */
5070     static void
5071 gfp_setname(char_u *fname, void *cookie)
5072 {
5073     char_u	*gfp_buffer = cookie;
5074 
5075     if (STRLEN(fname) >= MAXPATHL)
5076 	*gfp_buffer = NUL;
5077     else
5078 	STRCPY(gfp_buffer, fname);
5079 }
5080 
5081 /*
5082  * Find the path of bitmap "name" with extension "ext" in 'runtimepath'.
5083  * Return FAIL for failure and OK if buffer[MAXPATHL] contains the result.
5084  */
5085     int
5086 gui_find_bitmap(char_u *name, char_u *buffer, char *ext)
5087 {
5088     if (STRLEN(name) > MAXPATHL - 14)
5089 	return FAIL;
5090     vim_snprintf((char *)buffer, MAXPATHL, "bitmaps/%s.%s", name, ext);
5091     if (do_in_runtimepath(buffer, 0, gfp_setname, buffer) == FAIL
5092 							    || *buffer == NUL)
5093 	return FAIL;
5094     return OK;
5095 }
5096 
5097 # if !defined(FEAT_GUI_GTK) || defined(PROTO)
5098 /*
5099  * Given the name of the "icon=" argument, try finding the bitmap file for the
5100  * icon.  If it is an absolute path name, use it as it is.  Otherwise append
5101  * "ext" and search for it in 'runtimepath'.
5102  * The result is put in "buffer[MAXPATHL]".  If something fails "buffer"
5103  * contains "name".
5104  */
5105     void
5106 gui_find_iconfile(char_u *name, char_u *buffer, char *ext)
5107 {
5108     char_u	buf[MAXPATHL + 1];
5109 
5110     expand_env(name, buffer, MAXPATHL);
5111     if (!mch_isFullName(buffer) && gui_find_bitmap(buffer, buf, ext) == OK)
5112 	STRCPY(buffer, buf);
5113 }
5114 # endif
5115 #endif
5116 
5117 #if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_X11)|| defined(FEAT_GUI_HAIKU) \
5118 	|| defined(PROTO)
5119     void
5120 display_errors(void)
5121 {
5122     char_u	*p;
5123 
5124     if (isatty(2))
5125 	fflush(stderr);
5126     else if (error_ga.ga_data != NULL)
5127     {
5128 	// avoid putting up a message box with blanks only
5129 	for (p = (char_u *)error_ga.ga_data; *p != NUL; ++p)
5130 	    if (!isspace(*p))
5131 	    {
5132 		// Truncate a very long message, it will go off-screen.
5133 		if (STRLEN(p) > 2000)
5134 		    STRCPY(p + 2000 - 14, "...(truncated)");
5135 		(void)do_dialog(VIM_ERROR, (char_u *)_("Error"),
5136 				       p, (char_u *)_("&Ok"), 1, NULL, FALSE);
5137 		break;
5138 	    }
5139 	ga_clear(&error_ga);
5140     }
5141 }
5142 #endif
5143 
5144 #if defined(NO_CONSOLE_INPUT) || defined(PROTO)
5145 /*
5146  * Return TRUE if still starting up and there is no place to enter text.
5147  * For GTK and X11 we check if stderr is not a tty, which means we were
5148  * (probably) started from the desktop.  Also check stdin, "vim >& file" does
5149  * allow typing on stdin.
5150  */
5151     int
5152 no_console_input(void)
5153 {
5154     return ((!gui.in_use || gui.starting)
5155 # ifndef NO_CONSOLE
5156 	    && !isatty(0) && !isatty(2)
5157 # endif
5158 	    );
5159 }
5160 #endif
5161 
5162 #if defined(FIND_REPLACE_DIALOG) \
5163 	|| defined(NEED_GUI_UPDATE_SCREEN) \
5164 	|| defined(PROTO)
5165 /*
5166  * Update the current window and the screen.
5167  */
5168     void
5169 gui_update_screen(void)
5170 {
5171 # ifdef FEAT_CONCEAL
5172     linenr_T	conceal_old_cursor_line = 0;
5173     linenr_T	conceal_new_cursor_line = 0;
5174     int		conceal_update_lines = FALSE;
5175 # endif
5176 
5177     update_topline();
5178     validate_cursor();
5179 
5180     // Trigger CursorMoved if the cursor moved.
5181     if (!finish_op && (has_cursormoved()
5182 # ifdef FEAT_PROP_POPUP
5183 		|| popup_visible
5184 # endif
5185 # ifdef FEAT_CONCEAL
5186 		|| curwin->w_p_cole > 0
5187 # endif
5188 		) && !EQUAL_POS(last_cursormoved, curwin->w_cursor))
5189     {
5190 	if (has_cursormoved())
5191 	    apply_autocmds(EVENT_CURSORMOVED, NULL, NULL, FALSE, curbuf);
5192 #ifdef FEAT_PROP_POPUP
5193 	if (popup_visible)
5194 	    popup_check_cursor_pos();
5195 #endif
5196 # ifdef FEAT_CONCEAL
5197 	if (curwin->w_p_cole > 0)
5198 	{
5199 	    conceal_old_cursor_line = last_cursormoved.lnum;
5200 	    conceal_new_cursor_line = curwin->w_cursor.lnum;
5201 	    conceal_update_lines = TRUE;
5202 	}
5203 # endif
5204 	last_cursormoved = curwin->w_cursor;
5205     }
5206 
5207 # ifdef FEAT_CONCEAL
5208     if (conceal_update_lines
5209 	    && (conceal_old_cursor_line != conceal_new_cursor_line
5210 		|| conceal_cursor_line(curwin)
5211 		|| need_cursor_line_redraw))
5212     {
5213 	if (conceal_old_cursor_line != conceal_new_cursor_line)
5214 	    redrawWinline(curwin, conceal_old_cursor_line);
5215 	redrawWinline(curwin, conceal_new_cursor_line);
5216 	curwin->w_valid &= ~VALID_CROW;
5217 	need_cursor_line_redraw = FALSE;
5218     }
5219 # endif
5220     update_screen(0);	// may need to update the screen
5221     setcursor();
5222     out_flush_cursor(TRUE, FALSE);
5223 }
5224 #endif
5225 
5226 #if defined(FIND_REPLACE_DIALOG) || defined(PROTO)
5227 /*
5228  * Get the text to use in a find/replace dialog.  Uses the last search pattern
5229  * if the argument is empty.
5230  * Returns an allocated string.
5231  */
5232     char_u *
5233 get_find_dialog_text(
5234     char_u	*arg,
5235     int		*wwordp,	// return: TRUE if \< \> found
5236     int		*mcasep)	// return: TRUE if \C found
5237 {
5238     char_u	*text;
5239 
5240     if (*arg == NUL)
5241 	text = last_search_pat();
5242     else
5243 	text = arg;
5244     if (text != NULL)
5245     {
5246 	text = vim_strsave(text);
5247 	if (text != NULL)
5248 	{
5249 	    int len = (int)STRLEN(text);
5250 	    int i;
5251 
5252 	    // Remove "\V"
5253 	    if (len >= 2 && STRNCMP(text, "\\V", 2) == 0)
5254 	    {
5255 		mch_memmove(text, text + 2, (size_t)(len - 1));
5256 		len -= 2;
5257 	    }
5258 
5259 	    // Recognize "\c" and "\C" and remove.
5260 	    if (len >= 2 && *text == '\\' && (text[1] == 'c' || text[1] == 'C'))
5261 	    {
5262 		*mcasep = (text[1] == 'C');
5263 		mch_memmove(text, text + 2, (size_t)(len - 1));
5264 		len -= 2;
5265 	    }
5266 
5267 	    // Recognize "\<text\>" and remove.
5268 	    if (len >= 4
5269 		    && STRNCMP(text, "\\<", 2) == 0
5270 		    && STRNCMP(text + len - 2, "\\>", 2) == 0)
5271 	    {
5272 		*wwordp = TRUE;
5273 		mch_memmove(text, text + 2, (size_t)(len - 4));
5274 		text[len - 4] = NUL;
5275 	    }
5276 
5277 	    // Recognize "\/" or "\?" and remove.
5278 	    for (i = 0; i + 1 < len; ++i)
5279 		if (text[i] == '\\' && (text[i + 1] == '/'
5280 						       || text[i + 1] == '?'))
5281 		{
5282 		    mch_memmove(text + i, text + i + 1, (size_t)(len - i));
5283 		    --len;
5284 		}
5285 	}
5286     }
5287     return text;
5288 }
5289 
5290 /*
5291  * Handle the press of a button in the find-replace dialog.
5292  * Return TRUE when something was added to the input buffer.
5293  */
5294     int
5295 gui_do_findrepl(
5296     int		flags,		// one of FRD_REPLACE, FRD_FINDNEXT, etc.
5297     char_u	*find_text,
5298     char_u	*repl_text,
5299     int		down)		// Search downwards.
5300 {
5301     garray_T	ga;
5302     int		i;
5303     int		type = (flags & FRD_TYPE_MASK);
5304     char_u	*p;
5305     regmatch_T	regmatch;
5306     int		save_did_emsg = did_emsg;
5307     static int  busy = FALSE;
5308 
5309     // When the screen is being updated we should not change buffers and
5310     // windows structures, it may cause freed memory to be used.  Also don't
5311     // do this recursively (pressing "Find" quickly several times.
5312     if (updating_screen || busy)
5313 	return FALSE;
5314 
5315     // refuse replace when text cannot be changed
5316     if ((type == FRD_REPLACE || type == FRD_REPLACEALL) && text_locked())
5317 	return FALSE;
5318 
5319     busy = TRUE;
5320 
5321     ga_init2(&ga, 1, 100);
5322     if (type == FRD_REPLACEALL)
5323 	ga_concat(&ga, (char_u *)"%s/");
5324 
5325     ga_concat(&ga, (char_u *)"\\V");
5326     if (flags & FRD_MATCH_CASE)
5327 	ga_concat(&ga, (char_u *)"\\C");
5328     else
5329 	ga_concat(&ga, (char_u *)"\\c");
5330     if (flags & FRD_WHOLE_WORD)
5331 	ga_concat(&ga, (char_u *)"\\<");
5332     // escape slash and backslash
5333     p = vim_strsave_escaped(find_text, (char_u *)"/\\");
5334     if (p != NULL)
5335         ga_concat(&ga, p);
5336     vim_free(p);
5337     if (flags & FRD_WHOLE_WORD)
5338 	ga_concat(&ga, (char_u *)"\\>");
5339 
5340     if (type == FRD_REPLACEALL)
5341     {
5342 	ga_concat(&ga, (char_u *)"/");
5343 	// escape slash and backslash
5344 	p = vim_strsave_escaped(repl_text, (char_u *)"/\\");
5345 	if (p != NULL)
5346 	    ga_concat(&ga, p);
5347 	vim_free(p);
5348 	ga_concat(&ga, (char_u *)"/g");
5349     }
5350     ga_append(&ga, NUL);
5351 
5352     if (type == FRD_REPLACE)
5353     {
5354 	// Do the replacement when the text at the cursor matches.  Thus no
5355 	// replacement is done if the cursor was moved!
5356 	regmatch.regprog = vim_regcomp(ga.ga_data, RE_MAGIC + RE_STRING);
5357 	regmatch.rm_ic = 0;
5358 	if (regmatch.regprog != NULL)
5359 	{
5360 	    p = ml_get_cursor();
5361 	    if (vim_regexec_nl(&regmatch, p, (colnr_T)0)
5362 						   && regmatch.startp[0] == p)
5363 	    {
5364 		// Clear the command line to remove any old "No match"
5365 		// error.
5366 		msg_end_prompt();
5367 
5368 		if (u_save_cursor() == OK)
5369 		{
5370 		    // A button was pressed thus undo should be synced.
5371 		    u_sync(FALSE);
5372 
5373 		    del_bytes((long)(regmatch.endp[0] - regmatch.startp[0]),
5374 								FALSE, FALSE);
5375 		    ins_str(repl_text);
5376 		}
5377 	    }
5378 	    else
5379 		msg(_("No match at cursor, finding next"));
5380 	    vim_regfree(regmatch.regprog);
5381 	}
5382     }
5383 
5384     if (type == FRD_REPLACEALL)
5385     {
5386 	// A button was pressed, thus undo should be synced.
5387 	u_sync(FALSE);
5388 	do_cmdline_cmd(ga.ga_data);
5389     }
5390     else
5391     {
5392 	int searchflags = SEARCH_MSG + SEARCH_MARK;
5393 
5394 	// Search for the next match.
5395 	// Don't skip text under cursor for single replace.
5396 	if (type == FRD_REPLACE)
5397 	    searchflags += SEARCH_START;
5398 	i = msg_scroll;
5399 	if (down)
5400 	{
5401 	    (void)do_search(NULL, '/', '/', ga.ga_data, 1L, searchflags, NULL);
5402 	}
5403 	else
5404 	{
5405 	    // We need to escape '?' if and only if we are searching in the up
5406 	    // direction
5407 	    p = vim_strsave_escaped(ga.ga_data, (char_u *)"?");
5408 	    if (p != NULL)
5409 	        (void)do_search(NULL, '?', '?', p, 1L, searchflags, NULL);
5410 	    vim_free(p);
5411 	}
5412 
5413 	msg_scroll = i;	    // don't let an error message set msg_scroll
5414     }
5415 
5416     // Don't want to pass did_emsg to other code, it may cause disabling
5417     // syntax HL if we were busy redrawing.
5418     did_emsg = save_did_emsg;
5419 
5420     if (State & (NORMAL | INSERT))
5421     {
5422 	gui_update_screen();		// update the screen
5423 	msg_didout = 0;			// overwrite any message
5424 	need_wait_return = FALSE;	// don't wait for return
5425     }
5426 
5427     vim_free(ga.ga_data);
5428     busy = FALSE;
5429     return (ga.ga_len > 0);
5430 }
5431 
5432 #endif
5433 
5434 #if defined(HAVE_DROP_FILE) || defined(PROTO)
5435 /*
5436  * Jump to the window at specified point (x, y).
5437  */
5438     static void
5439 gui_wingoto_xy(int x, int y)
5440 {
5441     int		row = Y_2_ROW(y);
5442     int		col = X_2_COL(x);
5443     win_T	*wp;
5444 
5445     if (row >= 0 && col >= 0)
5446     {
5447 	wp = mouse_find_win(&row, &col, FAIL_POPUP);
5448 	if (wp != NULL && wp != curwin)
5449 	    win_goto(wp);
5450     }
5451 }
5452 
5453 /*
5454  * Function passed to handle_drop() for the actions to be done after the
5455  * argument list has been updated.
5456  */
5457     static void
5458 drop_callback(void *cookie)
5459 {
5460     char_u	*p = cookie;
5461 
5462     // If Shift held down, change to first file's directory.  If the first
5463     // item is a directory, change to that directory (and let the explorer
5464     // plugin show the contents).
5465     if (p != NULL)
5466     {
5467 	if (mch_isdir(p))
5468 	{
5469 	    if (mch_chdir((char *)p) == 0)
5470 		shorten_fnames(TRUE);
5471 	}
5472 	else if (vim_chdirfile(p, "drop") == OK)
5473 	    shorten_fnames(TRUE);
5474 	vim_free(p);
5475     }
5476 
5477     // Update the screen display
5478     update_screen(NOT_VALID);
5479 # ifdef FEAT_MENU
5480     gui_update_menus(0);
5481 # endif
5482 #ifdef FEAT_TITLE
5483     maketitle();
5484 #endif
5485     setcursor();
5486     out_flush_cursor(FALSE, FALSE);
5487 }
5488 
5489 /*
5490  * Process file drop.  Mouse cursor position, key modifiers, name of files
5491  * and count of files are given.  Argument "fnames[count]" has full pathnames
5492  * of dropped files, they will be freed in this function, and caller can't use
5493  * fnames after call this function.
5494  */
5495     void
5496 gui_handle_drop(
5497     int		x UNUSED,
5498     int		y UNUSED,
5499     int_u	modifiers,
5500     char_u	**fnames,
5501     int		count)
5502 {
5503     int		i;
5504     char_u	*p;
5505     static int	entered = FALSE;
5506 
5507     /*
5508      * This function is called by event handlers.  Just in case we get a
5509      * second event before the first one is handled, ignore the second one.
5510      * Not sure if this can ever happen, just in case.
5511      */
5512     if (entered)
5513 	return;
5514     entered = TRUE;
5515 
5516     /*
5517      * When the cursor is at the command line, add the file names to the
5518      * command line, don't edit the files.
5519      */
5520     if (State & CMDLINE)
5521     {
5522 	shorten_filenames(fnames, count);
5523 	for (i = 0; i < count; ++i)
5524 	{
5525 	    if (fnames[i] != NULL)
5526 	    {
5527 		if (i > 0)
5528 		    add_to_input_buf((char_u*)" ", 1);
5529 
5530 		// We don't know what command is used thus we can't be sure
5531 		// about which characters need to be escaped.  Only escape the
5532 		// most common ones.
5533 # ifdef BACKSLASH_IN_FILENAME
5534 		p = vim_strsave_escaped(fnames[i], (char_u *)" \t\"|");
5535 # else
5536 		p = vim_strsave_escaped(fnames[i], (char_u *)"\\ \t\"|");
5537 # endif
5538 		if (p != NULL)
5539 		    add_to_input_buf_csi(p, (int)STRLEN(p));
5540 		vim_free(p);
5541 		vim_free(fnames[i]);
5542 	    }
5543 	}
5544 	vim_free(fnames);
5545     }
5546     else
5547     {
5548 	// Go to the window under mouse cursor, then shorten given "fnames" by
5549 	// current window, because a window can have local current dir.
5550 	gui_wingoto_xy(x, y);
5551 	shorten_filenames(fnames, count);
5552 
5553 	// If Shift held down, remember the first item.
5554 	if ((modifiers & MOUSE_SHIFT) != 0)
5555 	    p = vim_strsave(fnames[0]);
5556 	else
5557 	    p = NULL;
5558 
5559 	// Handle the drop, :edit or :split to get to the file.  This also
5560 	// frees fnames[].  Skip this if there is only one item, it's a
5561 	// directory and Shift is held down.
5562 	if (count == 1 && (modifiers & MOUSE_SHIFT) != 0
5563 						     && mch_isdir(fnames[0]))
5564 	{
5565 	    vim_free(fnames[0]);
5566 	    vim_free(fnames);
5567 	}
5568 	else
5569 	    handle_drop(count, fnames, (modifiers & MOUSE_CTRL) != 0,
5570 		    drop_callback, (void *)p);
5571     }
5572 
5573     entered = FALSE;
5574 }
5575 #endif
5576 
5577 /*
5578  * Check if "key" is to interrupt us.  Handles a key that has not had modifiers
5579  * applied yet.
5580  * Return the key with modifiers applied if so, NUL if not.
5581  */
5582     int
5583 check_for_interrupt(int key, int modifiers_arg)
5584 {
5585     int modifiers = modifiers_arg;
5586     int c = merge_modifyOtherKeys(key, &modifiers);
5587 
5588     if ((c == Ctrl_C && ctrl_c_interrupts)
5589 #ifdef UNIX
5590 	    || (intr_char != Ctrl_C && c == intr_char)
5591 #endif
5592 	    )
5593     {
5594 	got_int = TRUE;
5595 	return c;
5596     }
5597     return NUL;
5598 }
5599 
5600