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