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