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