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