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