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