robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
64.1 KiB2066 linesraw
1#include <assert.h>
2#include <stdbool.h>
3#include <stdint.h>
4#include <stdlib.h>
5#include <string.h>
6
7#include "nvim/ascii_defs.h"
8#include "nvim/buffer.h"
9#include "nvim/buffer_defs.h"
10#include "nvim/charset.h"
11#include "nvim/cmdexpand.h"
12#include "nvim/cursor.h"
13#include "nvim/decoration.h"
14#include "nvim/diff.h"
15#include "nvim/drawscreen.h"
16#include "nvim/eval.h"
17#include "nvim/eval/typval.h"
18#include "nvim/eval/vars.h"
19#include "nvim/ex_docmd.h"
20#include "nvim/fold.h"
21#include "nvim/globals.h"
22#include "nvim/grid.h"
23#include "nvim/grid_defs.h"
24#include "nvim/input.h"
25#include "nvim/input_cmdatom.h"
26#include "nvim/insert.h"
27#include "nvim/keycodes.h"
28#include "nvim/macros_defs.h"
29#include "nvim/mark_defs.h"
30#include "nvim/mbyte.h"
31#include "nvim/mbyte_defs.h"
32#include "nvim/mcursor.h"
33#include "nvim/memline.h"
34#include "nvim/memory.h"
35#include "nvim/menu.h"
36#include "nvim/message.h"
37#include "nvim/mouse.h"
38#include "nvim/move.h"
39#include "nvim/normal.h"
40#include "nvim/ops.h"
41#include "nvim/option.h"
42#include "nvim/option_vars.h"
43#include "nvim/plines.h"
44#include "nvim/popupmenu.h"
45#include "nvim/pos_defs.h"
46#include "nvim/register.h"
47#include "nvim/search.h"
48#include "nvim/state.h"
49#include "nvim/state_defs.h"
50#include "nvim/statusline.h"
51#include "nvim/statusline_defs.h"
52#include "nvim/strings.h"
53#include "nvim/types_defs.h"
54#include "nvim/ui.h"
55#include "nvim/ui_compositor.h"
56#include "nvim/vim_defs.h"
57#include "nvim/window.h"
58
59#include "mouse.c.generated.h"
60
61static linenr_T orig_topline = 0;
62static int orig_topfill = 0;
63
64/// Get class of a character for selection: same class means same word.
65/// 0: blank
66/// 1: punctuation groups
67/// 2: normal word character
68/// >2: multi-byte word character.
69static int get_mouse_class(char *p)
70{
71  if (MB_BYTE2LEN((uint8_t)p[0]) > 1) {
72    return mb_get_class(p);
73  }
74
75  const int c = (uint8_t)(*p);
76  if (c == ' ' || c == '\t') {
77    return 0;
78  }
79  if (vim_iswordc(c)) {
80    return 2;
81  }
82
83  // There are a few special cases where we want certain combinations of
84  // characters to be considered as a single word.  These are things like
85  // "->", "/ *", "*=", "+=", "&=", "<=", ">=", "!=" etc.  Otherwise, each
86  // character is in its own class.
87  if (c != NUL && vim_strchr("-+*/%<>&|^!=", c) != NULL) {
88    return 1;
89  }
90  return c;
91}
92
93/// Move "pos" back to the start of the word it's in.
94static void find_start_of_word(pos_T *pos)
95{
96  char *line = ml_get(pos->lnum);
97  int cclass = get_mouse_class(line + pos->col);
98
99  while (pos->col > 0) {
100    int col = pos->col - 1;
101    col -= utf_head_off(line, line + col);
102    if (get_mouse_class(line + col) != cclass) {
103      break;
104    }
105    pos->col = col;
106  }
107}
108
109/// Move "pos" forward to the end of the word it's in.
110/// When 'selection' is "exclusive", the position is just after the word.
111static void find_end_of_word(pos_T *pos)
112{
113  char *line = ml_get(pos->lnum);
114  if (*p_sel == 'e' && pos->col > 0) {
115    pos->col--;
116    pos->col -= utf_head_off(line, line + pos->col);
117  }
118  int cclass = get_mouse_class(line + pos->col);
119  while (line[pos->col] != NUL) {
120    int col = pos->col + utfc_ptr2len(line + pos->col);
121    if (get_mouse_class(line + col) != cclass) {
122      if (*p_sel == 'e') {
123        pos->col = col;
124      }
125      break;
126    }
127    pos->col = col;
128  }
129}
130
131/// Move the current tab to tab in same column as mouse or to end of the
132/// tabline if there is no tab there.
133static void move_tab_to_mouse(void)
134{
135  int tabnr = tab_page_click_defs[mouse_col].tabnr;
136  if (tabnr <= 0) {
137    tabpage_move(9999);
138  } else if (tabnr < tabpage_index(curtab)) {
139    tabpage_move(tabnr - 1);
140  } else {
141    tabpage_move(tabnr);
142  }
143}
144/// Close the current or specified tab page.
145///
146/// @param c1  tabpage number, or 999 for the current tabpage
147static void mouse_tab_close(int c1)
148{
149  tabpage_T *tp;
150
151  if (c1 == 999) {
152    tp = curtab;
153  } else {
154    tp = find_tabpage(c1);
155  }
156  if (tp == curtab) {
157    if (first_tabpage->tp_next != NULL) {
158      tabpage_close(false);
159    }
160  } else if (tp != NULL) {
161    tabpage_close_other(tp, false);
162  }
163}
164
165static bool got_click = false;  // got a click some time back
166
167/// Call click definition function for column "col" in the "click_defs" array for button
168/// "which_button".
169static void call_click_def_func(StlClickDefinition *click_defs, int col, int which_button)
170{
171  typval_T argv[] = {
172    {
173      .v_lock = VAR_FIXED,
174      .v_type = VAR_NUMBER,
175      .vval = {
176        .v_number = (varnumber_T)click_defs[col].tabnr
177      },
178    },
179    {
180      .v_lock = VAR_FIXED,
181      .v_type = VAR_NUMBER,
182      .vval = {
183        .v_number = ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_4CLICK
184                     ? 4
185                     : ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_3CLICK
186                        ? 3
187                        : ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK
188                           ? 2
189                           : 1)))
190      },
191    },
192    {
193      .v_lock = VAR_FIXED,
194      .v_type = VAR_STRING,
195      .vval = {
196        .v_string = (which_button == MOUSE_LEFT
197                     ? "l"
198                     : (which_button == MOUSE_RIGHT
199                        ? "r"
200                        : (which_button == MOUSE_MIDDLE
201                           ? "m"
202                           : (which_button == MOUSE_X1
203                              ? "x1"
204                              : (which_button == MOUSE_X2
205                                 ? "x2"
206                                 : "?")))))
207      },
208    },
209    {
210      .v_lock = VAR_FIXED,
211      .v_type = VAR_STRING,
212      .vval = {
213        .v_string = (char[]) {
214          (char)(mod_mask & MOD_MASK_SHIFT ? 's' : ' '),
215          (char)(mod_mask & MOD_MASK_CTRL ? 'c' : ' '),
216          (char)(mod_mask & MOD_MASK_ALT ? 'a' : ' '),
217          (char)(mod_mask & MOD_MASK_META ? 'm' : ' '),
218          NUL
219        }
220      },
221    }
222  };
223  typval_T rettv;
224  call_vim_function(click_defs[col].func, ARRAY_SIZE(argv), argv, &rettv);
225  tv_clear(&rettv);
226  // Make sure next click does not register as drag when callback absorbs the release event.
227  got_click = false;
228}
229
230/// Translate window coordinates to buffer position without any side effects.
231/// Returns IN_BUFFER and sets `mpos` (0-based column) when in buffer text.
232///
233/// @param wpp  If not NULL: consider any window (not just `curwin`), and return it here.
234static int get_fpos_of_mouse(pos_T *mpos, win_T **wpp)
235{
236  int grid = mouse_grid;
237  int row = mouse_row;
238  int col = mouse_col;
239
240  if (row < 0 || col < 0) {  // check if it makes sense
241    return IN_UNKNOWN;
242  }
243
244  // find the window where the row is in
245  win_T *wp = mouse_find_win_inner(&grid, &row, &col);
246  if (wp == NULL) {
247    return IN_UNKNOWN;
248  }
249  if (wpp != NULL) {
250    *wpp = wp;
251  }
252  int winrow = row;
253  int wincol = col;
254
255  // compute the position in the buffer line from the posn on the screen
256  bool below_buffer = mouse_comp_pos(wp, &row, &col, &mpos->lnum);
257
258  if (!below_buffer && *wp->w_p_stc != NUL
259      && (wp->w_p_rl
260          ? wincol >= wp->w_view_width - win_col_off(wp)
261          : wincol < win_col_off(wp))) {
262    return MOUSE_STATUSCOL;
263  }
264
265  // winpos and height may change in win_enter()!
266  if (winrow >= wp->w_view_height + wp->w_status_height) {  // Below window
267    if (mouse_grid <= 1 && mouse_row < Rows - p_ch
268        && mouse_row >= Rows - p_ch - global_stl_height()) {  // In global status line
269      return IN_STATUS_LINE;
270    }
271    return IN_UNKNOWN;
272  } else if (winrow >= wp->w_view_height) {  // In window status line
273    return IN_STATUS_LINE;
274  }
275
276  if (winrow < 0 && winrow + wp->w_winbar_height >= 0) {  // In winbar
277    return MOUSE_WINBAR;
278  }
279
280  if (wincol >= wp->w_view_width) {  // In vertical separator line
281    return IN_SEP_LINE;
282  }
283
284  if ((wpp == NULL && wp != curwin) || below_buffer) {
285    return IN_UNKNOWN;
286  }
287
288  mpos->col = vcol2col(wp, mpos->lnum, col, &mpos->coladd);
289  return IN_BUFFER;
290}
291
292static int do_popup(int which_button, int m_pos_flag, pos_T m_pos)
293{
294  int jump_flags = 0;
295  if (strcmp(p_mousem, "popup_setpos") == 0) {
296    // First set the cursor position before showing the popup menu.
297    if (Visual.active) {
298      // set MOUSE_MAY_STOP_VIS if we are outside the selection
299      // or the current window (might have false negative here)
300      if (m_pos_flag != IN_BUFFER) {
301        jump_flags = MOUSE_MAY_STOP_VIS;
302      } else {
303        if (Visual.mode == 'V') {
304          if ((curwin->w_cursor.lnum <= Visual.start.lnum
305               && (m_pos.lnum < curwin->w_cursor.lnum || Visual.start.lnum < m_pos.lnum))
306              || (Visual.start.lnum < curwin->w_cursor.lnum
307                  && (m_pos.lnum < Visual.start.lnum || curwin->w_cursor.lnum < m_pos.lnum))) {
308            jump_flags = MOUSE_MAY_STOP_VIS;
309          }
310        } else if ((ltoreq(curwin->w_cursor, Visual.start)
311                    && (lt(m_pos, curwin->w_cursor) || lt(Visual.start, m_pos)))
312                   || (lt(Visual.start, curwin->w_cursor)
313                       && (lt(m_pos, Visual.start) || lt(curwin->w_cursor, m_pos)))) {
314          jump_flags = MOUSE_MAY_STOP_VIS;
315        } else if (Visual.mode == Ctrl_V) {
316          colnr_T leftcol, rightcol;
317          getvcols(curwin, &curwin->w_cursor, &Visual.start, &leftcol, &rightcol, 0);
318          getvcol(curwin, &m_pos, NULL, &m_pos.col, NULL, 0);
319          if (m_pos.col < leftcol || m_pos.col > rightcol) {
320            jump_flags = MOUSE_MAY_STOP_VIS;
321          }
322        }
323      }
324    } else {
325      jump_flags = MOUSE_MAY_STOP_VIS;
326    }
327  }
328  if (jump_flags) {
329    jump_flags = jump_to_mouse(jump_flags, NULL, which_button);
330    redraw_curbuf_later(Visual.active ? UPD_INVERTED : UPD_VALID);
331    update_screen();
332    setcursor();
333    ui_flush();  // Update before showing popup menu
334  }
335  show_popupmenu();
336  got_click = false;  // ignore release events
337  return jump_flags;
338}
339
340/// Do the appropriate action for the current mouse click in the current mode.
341/// Not used for Command-line mode. Per-mode/button behavior: |mouse-mode-table|.
342///
343/// @param oap        operator argument, can be NULL
344/// @param c          K_LEFTMOUSE, etc
345/// @param dir        Direction to 'put' if necessary
346/// @param fixindent  PUT_FIXINDENT if fixing indent necessary
347///
348/// @return           true if start_arrow() should be called for edit mode.
349bool do_mouse(oparg_T *oap, int c, int dir, int count, bool fixindent)
350{
351  int which_button;             // MOUSE_LEFT, _MIDDLE or _RIGHT
352  bool is_click;                // If false it's a drag or release event
353  bool is_drag;                 // If true it's a drag event
354  static bool in_tab_line = false;   // mouse clicked in tab line
355  static pos_T orig_cursor;
356
357  while (true) {
358    which_button = get_mouse_button(KEY2TERMCAP1(c), &is_click, &is_drag);
359    if (is_drag) {
360      // If the next character is the same mouse event then use that
361      // one. Speeds up dragging the status line.
362      // Note: Since characters added to the stuff buffer in the code
363      // below need to come before the next character, do not do this
364      // when the current character was stuffed.
365      if (!KeyStuffed && vpeekc() != NUL) {
366        int nc;
367        int save_mouse_grid = mouse_grid;
368        int save_mouse_row = mouse_row;
369        int save_mouse_col = mouse_col;
370
371        // Need to get the character, peeking doesn't get the actual one.
372        nc = safe_vgetc();
373        if (c == nc) {
374          continue;
375        }
376        vungetc(nc);
377        mouse_grid = save_mouse_grid;
378        mouse_row = save_mouse_row;
379        mouse_col = save_mouse_col;
380      }
381    }
382    break;
383  }
384
385  if (c == K_MOUSEMOVE) {
386    // Mouse moved without a button pressed.
387    return false;
388  }
389
390  // Ignore drag and release events if we didn't get a click.
391  if (is_click) {
392    got_click = true;
393    in_tab_line = false;
394  } else {
395    if (!got_click) {                   // didn't get click, ignore
396      return false;
397    }
398    if (!is_drag) {                     // release, reset got_click
399      got_click = false;
400      if (in_tab_line) {
401        in_tab_line = false;
402        return false;
403      }
404    }
405  }
406
407  // CTRL right mouse button does CTRL-T
408  if (is_click && (mod_mask & MOD_MASK_CTRL) && which_button == MOUSE_RIGHT) {
409    if (State & MODE_INSERT) {
410      stuffcharReadbuff(Ctrl_O);
411    }
412    if (count > 1) {
413      stuffnumReadbuff(count);
414    }
415    stuffcharReadbuff(Ctrl_T);
416    got_click = false;            // ignore drag&release now
417    if ((State & MODE_INSERT) == 0) {
418      exec_stuffed(NULL);
419    }
420    return false;
421  }
422
423  // CTRL only works with left mouse button
424  if ((mod_mask & MOD_MASK_CTRL) && which_button != MOUSE_LEFT) {
425    return false;
426  }
427
428  // When a modifier is down, ignore drag and release events, as well as
429  // multiple clicks and the middle mouse button.
430  // Accept shift-leftmouse drags when 'mousemodel' is "popup.*".
431  if ((mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT
432                   | MOD_MASK_META))
433      && (!is_click
434          || (mod_mask & MOD_MASK_MULTI_CLICK)
435          || which_button == MOUSE_MIDDLE)
436      && !((mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT))
437           && mouse_model_popup()
438           && which_button == MOUSE_LEFT)
439      && !((mod_mask & MOD_MASK_ALT)
440           && !mouse_model_popup()
441           && which_button == MOUSE_RIGHT)) {
442    return false;
443  }
444
445  // If the button press was used as the movement command for an operator (eg
446  // "d<MOUSE>"), or it is the middle button that is held down, ignore
447  // drag/release events.
448  if (!is_click && which_button == MOUSE_MIDDLE) {
449    return false;
450  }
451
452  int regname = oap != NULL ? oap->regname : 0;
453  // Middle mouse button does a 'put' of the selected text
454  if (which_button == MOUSE_MIDDLE) {
455    if (State == MODE_NORMAL) {
456      // If an operator was pending, we don't know what the user wanted to do.
457      // Go back to normal mode: Clear the operator and beep().
458      if (oap != NULL && oap->op_type != OP_NOP) {
459        clearopbeep(oap);
460        return false;
461      }
462
463      // If visual was active, yank the highlighted text and put it
464      // before the mouse pointer position.
465      // In Select mode replace the highlighted text with the clipboard.
466      if (Visual.active) {
467        if (Visual.select) {
468          stuffcharReadbuff(Ctrl_G);
469          stuffReadbuff("\"+p");
470        } else {
471          // Reg prefix must travel in the keys run by exec_stuffed. E.g. `"ay<MiddleMouse>`
472          if (regname != 0) {
473            stuffcharReadbuff('"');
474            stuffcharReadbuff(regname);
475          }
476          stuffcharReadbuff('y');
477          stuffcharReadbuff(K_MIDDLEMOUSE);
478        }
479        exec_stuffed(NULL);
480        return false;
481      }
482      // The rest is below jump_to_mouse()
483    } else if ((State & MODE_INSERT) == 0) {
484      return false;
485    }
486
487    // Middle click in insert mode doesn't move the mouse, just insert the
488    // contents of a register.  '.' register is special, can't insert that
489    // with do_put().
490    // Also paste at the cursor if the current mode isn't in 'mouse' (only
491    // happens for the GUI).
492    if ((State & MODE_INSERT)) {
493      if (regname == '.') {
494        insert_reg(regname, NULL, true);
495      } else {
496        if (regname == 0 && eval_has_provider("clipboard", false)) {
497          regname = '*';
498        }
499        yankreg_T *reg = NULL;
500        if ((State & REPLACE_FLAG) && !yank_register_mline(regname, &reg)) {
501          insert_reg(regname, reg, true);
502        } else {
503          do_put(regname, reg, BACKWARD, 1,
504                 (fixindent ? PUT_FIXINDENT : 0) | PUT_CURSEND);
505
506          // Repeat it with CTRL-R CTRL-O r or CTRL-R CTRL-P r
507          redo_append_char(Ctrl_R);
508          redo_append_char(fixindent ? Ctrl_P : Ctrl_O);
509          redo_append_char(regname == 0 ? '"' : regname);
510        }
511      }
512      return false;
513    }
514  }
515
516  // flags for jump_to_mouse()
517  // When dragging or button-up stay in the same window.
518  int jump_flags = is_click ? 0 : (MOUSE_FOCUS|MOUSE_DID_MOVE);
519  win_T *old_curwin = curwin;
520
521  if (tab_page_click_defs != NULL) {  // only when initialized
522    // Check for clicking in the tab page line.
523    if (mouse_grid <= 1 && mouse_row == 0 && firstwin->w_winrow > 0) {
524      if (is_drag) {
525        if (in_tab_line) {
526          move_tab_to_mouse();
527        }
528        return false;
529      }
530
531      // click in a tab selects that tab page
532      if (is_click && mouse_col < Columns) {
533        int tabnr = tab_page_click_defs[mouse_col].tabnr;
534        in_tab_line = true;
535
536        switch (tab_page_click_defs[mouse_col].type) {
537        case kStlClickDisabled:
538          break;
539        case kStlClickTabSwitch:
540          if (which_button != MOUSE_MIDDLE) {
541            if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK) {
542              // double click opens new page
543              end_visual_mode();
544              tabpage_new();
545              tabpage_move(tabnr == 0 ? 9999 : tabnr - 1);
546            } else {
547              // Go to specified tab page, or next one if not clicking
548              // on a label.
549              goto_tabpage(tabnr);
550
551              // It's like clicking on the status line of a window.
552              if (curwin != old_curwin) {
553                end_visual_mode();
554              }
555            }
556            break;
557          }
558          FALLTHROUGH;
559        case kStlClickTabClose:
560          mouse_tab_close(tabnr);
561          break;
562        case kStlClickFuncRun:
563          call_click_def_func(tab_page_click_defs, mouse_col, which_button);
564          break;
565        }
566      }
567      return true;
568    } else if (is_drag && in_tab_line) {
569      move_tab_to_mouse();
570      return false;
571    }
572  }
573
574  // Multicursor: CTRL-click toggles a cursor at click pos, without moving the primary cursor.
575  // Not in quickfix: there CTRL-click jumps to the item. No-op during insert.
576  if (is_click && (mod_mask & MOD_MASK_CTRL) && which_button == MOUSE_LEFT) {
577    pos_T pos;
578    win_T *wp = NULL;
579    if (get_fpos_of_mouse(&pos, &wp) == IN_BUFFER && !bt_quickfix(wp->w_buffer)) {
580      got_click = false;  // ignore drag&release now
581      if ((State & MODE_INSERT) == 0) {
582        pos.coladd = 0;
583        mc_toggle(wp->w_buffer, pos, false, kNone);
584      }
585      return false;
586    }
587  }
588
589  int m_pos_flag = 0;
590  pos_T m_pos = { 0 };
591  // When 'mousemodel' is "popup" or "popup_setpos", translate mouse events:
592  // right button up   -> pop-up menu
593  // shift-left button -> right button
594  // alt-left button   -> alt-right button
595  if (mouse_model_popup()) {
596    m_pos_flag = get_fpos_of_mouse(&m_pos, NULL);
597    if (!(m_pos_flag & (IN_STATUS_LINE|MOUSE_WINBAR|MOUSE_STATUSCOL))
598        && which_button == MOUSE_RIGHT && !(mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))) {
599      if (!is_click) {
600        // Ignore right button release events, only shows the popup
601        // menu on the button down event.
602        return false;
603      }
604      return (do_popup(which_button, m_pos_flag, m_pos) & CURSOR_MOVED);
605    }
606    // Only do this translation when mouse is over the buffer text
607    if (!(m_pos_flag & (IN_STATUS_LINE|MOUSE_WINBAR|MOUSE_STATUSCOL))
608        && (which_button == MOUSE_LEFT && (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT)))) {
609      which_button = MOUSE_RIGHT;
610      mod_mask &= ~MOD_MASK_SHIFT;
611    }
612  }
613
614  pos_T end_visual = { 0 };
615  pos_T start_visual = { 0 };
616  bool mouse_can_visual = ui_mouse_has(kMouseVisual);
617  if ((State & (MODE_NORMAL | MODE_INSERT))
618      && !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))) {
619    if (which_button == MOUSE_LEFT && mouse_can_visual) {
620      if (is_click) {
621        // stop Visual mode for a left click in a window, but not when on a status line
622        if (Visual.active) {
623          jump_flags |= MOUSE_MAY_STOP_VIS;
624        }
625      } else {
626        jump_flags |= MOUSE_MAY_VIS;
627      }
628    } else if (which_button == MOUSE_RIGHT && mouse_can_visual) {
629      if (is_click && Visual.active) {
630        // Remember the start and end of visual before moving the cursor.
631        if (lt(curwin->w_cursor, Visual.start)) {
632          start_visual = curwin->w_cursor;
633          end_visual = Visual.start;
634        } else {
635          start_visual = Visual.start;
636          end_visual = curwin->w_cursor;
637        }
638      }
639      jump_flags |= MOUSE_MAY_VIS;
640      jump_flags |= MOUSE_FOCUS;
641    } else if (which_button == MOUSE_RIGHT) {
642      jump_flags |= MOUSE_FOCUS;
643    }
644  }
645
646  // If an operator is pending, ignore all drags and releases until the next mouse click.
647  if (!is_drag && oap != NULL && oap->op_type != OP_NOP) {
648    got_click = false;
649    oap->motion_type = kMTCharWise;
650  }
651
652  // When releasing the button let jump_to_mouse() know.
653  if (!is_click && !is_drag) {
654    jump_flags |= MOUSE_RELEASED;
655  }
656
657  // JUMP!
658  int old_active = Visual.active;
659  pos_T save_cursor = curwin->w_cursor;
660
661  // Even though we gate *_VIS flags above, we want to make sure the cursor doesn't move
662  // in visual mode unless it is set as a mouse option
663  if (!Visual.active || mouse_can_visual) {
664    jump_flags = jump_to_mouse(jump_flags, oap == NULL ? NULL : &(oap->inclusive), which_button);
665  }
666
667  if (mod_mask == 0
668      && !is_drag
669      && (jump_flags & (MOUSE_FOLD_CLOSE | MOUSE_FOLD_OPEN))
670      && which_button == MOUSE_LEFT) {
671    // open or close a fold at this line
672    if (jump_flags & MOUSE_FOLD_OPEN) {
673      openFold(curwin->w_cursor, 1);
674    } else {
675      closeFold(curwin->w_cursor, 1);
676    }
677    // don't move the cursor if still in the same window
678    if (curwin == old_curwin) {
679      curwin->w_cursor = save_cursor;
680    }
681  }
682
683  bool moved = (jump_flags & CURSOR_MOVED);
684  bool in_winbar = (jump_flags & MOUSE_WINBAR);
685  bool in_statuscol = (jump_flags & MOUSE_STATUSCOL);
686  bool in_status_line = (jump_flags & IN_STATUS_LINE);
687  bool in_global_statusline = in_status_line && global_stl_height() > 0;
688  bool in_sep_line = (jump_flags & IN_SEP_LINE);
689
690  if ((in_winbar || in_status_line || in_statuscol) && is_click) {
691    // Handle click event on window bar, status line or status column
692    int click_grid = mouse_grid;
693    int click_row = mouse_row;
694    int click_col = mouse_col;
695    win_T *wp = mouse_find_win_inner(&click_grid, &click_row, &click_col);
696    if (wp == NULL) {
697      return false;
698    }
699
700    StlClickDefinition *click_defs = in_status_line ? wp->w_status_click_defs
701                                                    : in_winbar ? wp->w_winbar_click_defs : NULL;
702    if (in_statuscol && wp->w_p_rl) {
703      click_col = wp->w_view_width - click_col - 1;
704    }
705
706    if (in_statuscol) {
707      int lnum = (int)get_vim_var_nr(VV_LNUM);
708      int virtnum = (int)get_vim_var_nr(VV_VIRTNUM);
709      StcClicks lnum_click_defs = map_get(int, StcClicks)(wp->w_statuscol_click_defs, lnum);
710      StcClick row_click_defs = map_get(int, StcClick)(&lnum_click_defs, virtnum);
711      if (click_col >= (int)row_click_defs.size) {
712        return false;
713      }
714      click_defs = row_click_defs.def;
715    }
716
717    if (in_global_statusline) {
718      // global statusline is displayed for the current window,
719      // and spans the whole screen.
720      click_defs = curwin->w_status_click_defs;
721      click_col = mouse_col;
722    }
723
724    if (in_status_line && click_col >=
725        (int)(in_global_statusline ? curwin : wp)->w_status_click_defs_size) {
726      return false;
727    }
728
729    if (click_defs != NULL) {
730      switch (click_defs[click_col].type) {
731      case kStlClickDisabled:
732        // If there is no click definition, still open the popupmenu for a
733        // statuscolumn click like a click in the sign/number column does.
734        if (in_statuscol && mouse_model_popup()
735            && which_button == MOUSE_RIGHT && !(mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))) {
736          do_popup(which_button, m_pos_flag, m_pos);
737        }
738        break;
739      case kStlClickFuncRun:
740        call_click_def_func(click_defs, click_col, which_button);
741        break;
742      default:
743        assert(false && "winbar, statusline and statuscolumn only support %@ for clicks");
744        break;
745      }
746    }
747    return false;
748  } else if (in_winbar || in_statuscol) {
749    // A drag or release event in the window bar and status column has no side effects.
750    return false;
751  }
752
753  // When jumping to another window, clear a pending operator.  That's a bit
754  // friendlier than beeping and not jumping to that window.
755  if (curwin != old_curwin && oap != NULL && oap->op_type != OP_NOP) {
756    clearop(oap);
757  }
758
759  // Set global flag that we are extending the Visual area with mouse dragging;
760  // temporarily minimize 'scrolloff'.
761  if (Visual.active && is_drag && get_scrolloff_value(curwin)) {
762    // In the very first line, allow scrolling one line
763    if (mouse_row == 0) {
764      mouse_dragging = 2;
765    } else {
766      mouse_dragging = 1;
767    }
768  }
769
770  // When dragging the mouse above the window, scroll down.
771  if (is_drag && mouse_row < 0 && !in_status_line) {
772    scroll_redraw(false, 1);
773    mouse_row = 0;
774  }
775
776  int old_mode = Visual.mode;
777  if (start_visual.lnum) {              // right click in visual mode
778    linenr_T diff;
779    // When ALT is pressed make Visual mode blockwise.
780    if (mod_mask & MOD_MASK_ALT) {
781      Visual.mode = Ctrl_V;
782    }
783
784    // In Visual-block mode, divide the area in four, pick up the corner
785    // that is in the quarter that the cursor is in.
786    if (Visual.mode == Ctrl_V) {
787      colnr_T leftcol, rightcol;
788      getvcols(curwin, &start_visual, &end_visual, &leftcol, &rightcol, 0);
789      if (curwin->w_curswant > (leftcol + rightcol) / 2) {
790        end_visual.col = leftcol;
791      } else {
792        end_visual.col = rightcol;
793      }
794      if (curwin->w_cursor.lnum >=
795          (start_visual.lnum + end_visual.lnum) / 2) {
796        end_visual.lnum = start_visual.lnum;
797      }
798
799      // move Visual.start to the right column
800      start_visual = curwin->w_cursor;              // save the cursor pos
801      curwin->w_cursor = end_visual;
802      coladvance(curwin, end_visual.col);
803      Visual.start = curwin->w_cursor;
804      curwin->w_cursor = start_visual;              // restore the cursor
805    } else {
806      // If the click is before the start of visual, change the start.
807      // If the click is after the end of visual, change the end.  If
808      // the click is inside the visual, change the closest side.
809      if (lt(curwin->w_cursor, start_visual)) {
810        Visual.start = end_visual;
811      } else if (lt(end_visual, curwin->w_cursor)) {
812        Visual.start = start_visual;
813      } else {
814        // In the same line, compare column number
815        if (end_visual.lnum == start_visual.lnum) {
816          if (curwin->w_cursor.col - start_visual.col >
817              end_visual.col - curwin->w_cursor.col) {
818            Visual.start = start_visual;
819          } else {
820            Visual.start = end_visual;
821          }
822        } else {
823          // In different lines, compare line number
824          diff = (curwin->w_cursor.lnum - start_visual.lnum) -
825                 (end_visual.lnum - curwin->w_cursor.lnum);
826
827          if (diff > 0) {                       // closest to end
828            Visual.start = start_visual;
829          } else if (diff < 0) {                   // closest to start
830            Visual.start = end_visual;
831          } else {                                // in the middle line
832            if (curwin->w_cursor.col <
833                (start_visual.col + end_visual.col) / 2) {
834              Visual.start = end_visual;
835            } else {
836              Visual.start = start_visual;
837            }
838          }
839        }
840      }
841    }
842  } else if ((State & MODE_INSERT) && Visual.active) {
843    // If Visual mode started in insert mode, execute "CTRL-O"
844    stuffcharReadbuff(Ctrl_O);
845  }
846
847  // Middle mouse click: Put text before cursor.
848  if (which_button == MOUSE_MIDDLE) {
849    if (regname == 0 && eval_has_provider("clipboard", false)) {
850      regname = '*';
851    }
852    yankreg_T *reg = NULL;
853    if (yank_register_mline(regname, &reg)) {
854      if (mouse_past_bottom) {
855        dir = FORWARD;
856      }
857    } else if (mouse_past_eol) {
858      dir = FORWARD;
859    }
860
861    int c1, c2;
862    if (fixindent) {
863      c1 = (dir == BACKWARD) ? '[' : ']';
864      c2 = 'p';
865    } else {
866      c1 = (dir == FORWARD) ? 'p' : 'P';
867      c2 = NUL;
868    }
869    prep_redo(true, false, (CmdSpec){ .regname = regname, .count = count, .cmd = c1, .cmd2 = c2 });
870
871    // Remember where the paste started, so in edit() Ins.start can be set to this position
872    if (restart_edit != 0) {
873      where_paste_started = curwin->w_cursor;
874    }
875    do_put(regname, reg, dir, count,
876           (fixindent ? PUT_FIXINDENT : 0)| PUT_CURSEND);
877  } else if (((mod_mask & MOD_MASK_CTRL) || (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
878             && bt_quickfix(curbuf)) {
879    // Ctrl-Mouse click or double click in a quickfix window jumps to the
880    // error under the mouse pointer.
881    if (curwin->w_llist_ref == NULL) {          // quickfix window
882      do_cmdline_cmd(".cc");
883    } else {                                    // location list window
884      do_cmdline_cmd(".ll");
885    }
886    got_click = false;                          // ignore drag&release now
887  } else if (curbuf->b_help && (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK) {
888    // Double-click in a help window jumps to the clicked tag.
889    if (State & MODE_INSERT) {
890      stuffcharReadbuff(Ctrl_O);
891    }
892    stuffcharReadbuff(Ctrl_RSB);
893    got_click = false;                          // ignore drag&release now
894    if ((State & MODE_INSERT) == 0) {
895      exec_stuffed(NULL);
896    }
897  } else if ((mod_mask & MOD_MASK_SHIFT)) {
898    // Shift-Mouse click searches for the next occurrence of the word under
899    // the mouse pointer
900    if (State & MODE_INSERT || (Visual.active && Visual.select)) {
901      stuffcharReadbuff(Ctrl_O);
902    }
903    if (which_button == MOUSE_LEFT) {
904      stuffcharReadbuff('*');
905    } else {  // MOUSE_RIGHT
906      stuffcharReadbuff('#');
907    }
908    if ((State & MODE_INSERT) == 0) {
909      exec_stuffed(NULL);
910    }
911  } else if (in_status_line || in_sep_line) {
912    // Do nothing if on status line or vertical separator
913    // Handle double clicks otherwise
914  } else if ((mod_mask & MOD_MASK_MULTI_CLICK) && (State & (MODE_NORMAL | MODE_INSERT))
915             && mouse_can_visual) {
916    if (is_click || !Visual.active) {
917      if (Visual.active) {
918        orig_cursor = Visual.start;
919      } else {
920        Visual.start = curwin->w_cursor;
921        orig_cursor = Visual.start;
922        Visual.active = true;
923        Visual.reselect = true;
924        // start Select mode if 'selectmode' contains "mouse"
925        may_start_select('o');
926        setmouse();
927      }
928      if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK) {
929        // Double click with ALT pressed makes it blockwise.
930        if (mod_mask & MOD_MASK_ALT) {
931          Visual.mode = Ctrl_V;
932        } else {
933          Visual.mode = 'v';
934        }
935      } else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_3CLICK) {
936        Visual.mode = 'V';
937      } else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_4CLICK) {
938        Visual.mode = Ctrl_V;
939      }
940    }
941    // A double click selects a word or a block.
942    if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK) {
943      pos_T *pos = NULL;
944
945      if (is_click) {
946        // If the character under the cursor (skipping white space) is
947        // not a word character, try finding a match and select a (),
948        // {}, [], #if/#endif, etc. block.
949        end_visual = curwin->w_cursor;
950        int gc;
951        while (gc = gchar_pos(&end_visual), ascii_iswhite(gc)) {
952          inc(&end_visual);
953        }
954        if (oap != NULL) {
955          oap->motion_type = kMTCharWise;
956        }
957        if (oap != NULL
958            && Visual.mode == 'v'
959            && !vim_iswordc(gchar_pos(&end_visual))
960            && equalpos(curwin->w_cursor, Visual.start)
961            && (pos = findmatch(oap, NUL)) != NULL) {
962          curwin->w_cursor = *pos;
963          if (oap->motion_type == kMTLineWise) {
964            Visual.mode = 'V';
965          } else if (*p_sel == 'e') {
966            if (lt(curwin->w_cursor, Visual.start)) {
967              Visual.start.col++;
968            } else {
969              curwin->w_cursor.col++;
970            }
971          }
972        }
973      }
974
975      if (pos == NULL && (is_click || is_drag)) {
976        // When not found a match or when dragging: extend to include a word.
977        if (lt(curwin->w_cursor, orig_cursor)) {
978          find_start_of_word(&curwin->w_cursor);
979          find_end_of_word(&Visual.start);
980        } else {
981          find_start_of_word(&Visual.start);
982          if (*p_sel == 'e' && *get_cursor_pos_ptr() != NUL) {
983            curwin->w_cursor.col +=
984              utfc_ptr2len(get_cursor_pos_ptr());
985          }
986          find_end_of_word(&curwin->w_cursor);
987        }
988      }
989      curwin->w_set_curswant = true;
990    }
991    if (is_click) {
992      redraw_curbuf_later(UPD_INVERTED);  // update the inversion
993    }
994  } else if (Visual.active && !old_active) {
995    if (mod_mask & MOD_MASK_ALT) {
996      Visual.mode = Ctrl_V;
997    } else {
998      Visual.mode = 'v';
999    }
1000  }
1001
1002  // If Visual mode changed show it later.
1003  if ((!Visual.active && old_active && mode_displayed)
1004      || (Visual.active && p_smd && msg_silent == 0
1005          && (!old_active || Visual.mode != old_mode))) {
1006    redraw_cmdline = true;
1007  }
1008
1009  return moved;
1010}
1011
1012void ins_mouse(int c)
1013{
1014  win_T *old_curwin = curwin;
1015
1016  undisplay_dollar();
1017  pos_T tpos = curwin->w_cursor;
1018  if (do_mouse(NULL, c, BACKWARD, 1, 0)) {
1019    win_T *new_curwin = curwin;
1020
1021    if (curwin != old_curwin && win_valid(old_curwin)) {
1022      // Mouse took us to another window.  We need to go back to the
1023      // previous one to stop insert there properly.
1024      curwin = old_curwin;
1025      curbuf = curwin->w_buffer;
1026      if (bt_prompt(curbuf)) {
1027        // Restart Insert mode when re-entering the prompt buffer.
1028        curbuf->b_prompt_insert = 'A';
1029      }
1030    }
1031    start_arrow(curwin == old_curwin ? &tpos : NULL, true, NUL);
1032    if (curwin != new_curwin && win_valid(new_curwin)) {
1033      curwin = new_curwin;
1034      curbuf = curwin->w_buffer;
1035    }
1036    set_can_cindent(true);
1037  }
1038
1039  // redraw status lines (in case another window became active)
1040  redraw_statuslines();
1041}
1042
1043/// Common mouse wheel scrolling, shared between Insert mode and NV modes.
1044/// Default action is to scroll mouse_vert_step lines (or mouse_hor_step columns
1045/// depending on the scroll direction) or one page when Shift or Ctrl is used.
1046/// Direction is indicated by "cap->arg":
1047///    K_MOUSEUP    - MSCR_UP
1048///    K_MOUSEDOWN  - MSCR_DOWN
1049///    K_MOUSELEFT  - MSCR_LEFT
1050///    K_MOUSERIGHT - MSCR_RIGHT
1051/// "curwin" may have been changed to the window that should be scrolled and
1052/// differ from the window that actually has focus.
1053void do_mousescroll(cmdarg_T *cap)
1054{
1055  bool shift_or_ctrl = mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL);
1056
1057  if (cap->arg == MSCR_UP || cap->arg == MSCR_DOWN) {
1058    // Vertical scrolling
1059    if ((State & MODE_NORMAL) && shift_or_ctrl) {
1060      // whole page up or down
1061      pagescroll(cap->arg ? FORWARD : BACKWARD, 1, false);
1062    } else {
1063      if (shift_or_ctrl) {
1064        // whole page up or down
1065        cap->count1 = curwin->w_botline - curwin->w_topline;
1066      } else {
1067        cap->count1 = (int)p_mousescroll_vert;
1068      }
1069      if (cap->count1 > 0) {
1070        cap->count0 = cap->count1;
1071        nv_scroll_line(cap);
1072      }
1073    }
1074  } else {
1075    // Horizontal scrolling
1076    int step = shift_or_ctrl ? curwin->w_view_width : (int)p_mousescroll_hor;
1077    colnr_T leftcol = curwin->w_leftcol + (cap->arg == MSCR_RIGHT ? -step : +step);
1078    leftcol = MAX(leftcol, 0);
1079    do_mousescroll_horiz(leftcol);
1080  }
1081}
1082
1083/// Implementation for scrolling in Insert mode in direction "dir", which is one
1084/// of the MSCR_ values.
1085void ins_mousescroll(int dir)
1086{
1087  cmdarg_T cap;
1088  oparg_T oa;
1089  CLEAR_FIELD(cap);
1090  clear_oparg(&oa);
1091  cap.oap = &oa;
1092  cap.arg = dir;
1093
1094  switch (dir) {
1095  case MSCR_UP:
1096    cap.cmdchar = K_MOUSEUP;
1097    break;
1098  case MSCR_DOWN:
1099    cap.cmdchar = K_MOUSEDOWN;
1100    break;
1101  case MSCR_LEFT:
1102    cap.cmdchar = K_MOUSELEFT;
1103    break;
1104  case MSCR_RIGHT:
1105    cap.cmdchar = K_MOUSERIGHT;
1106    break;
1107  default:
1108    siemsg("Invalid ins_mousescroll() argument: %d", dir);
1109  }
1110
1111  win_T *old_curwin = curwin;
1112  if (mouse_row >= 0 && mouse_col >= 0) {
1113    // Find the window at the mouse pointer coordinates.
1114    // NOTE: Must restore "curwin" to "old_curwin" before returning!
1115    int grid = mouse_grid;
1116    int row = mouse_row;
1117    int col = mouse_col;
1118    curwin = mouse_find_win_inner(&grid, &row, &col);
1119    if (curwin == NULL) {
1120      curwin = old_curwin;
1121      return;
1122    }
1123    curbuf = curwin->w_buffer;
1124  }
1125
1126  if (curwin == old_curwin) {
1127    // Don't scroll the current window if the popup menu is visible.
1128    if (pum_visible()) {
1129      return;
1130    }
1131
1132    undisplay_dollar();
1133  }
1134
1135  pos_T orig_cursor = curwin->w_cursor;
1136
1137  // Call the common mouse scroll function shared with other modes.
1138  do_mousescroll(&cap);
1139
1140  curwin->w_redr_status = true;
1141  curwin = old_curwin;
1142  curbuf = curwin->w_buffer;
1143
1144  if (!equalpos(curwin->w_cursor, orig_cursor)) {
1145    start_arrow(&orig_cursor, true, NUL);
1146    set_can_cindent(true);
1147  }
1148}
1149
1150/// Command-line mode implementation for scrolling in direction "dir", which is
1151/// one of the MSCR_ values.  Scrolls the completion info popup when the mouse
1152/// pointer is on top of it.
1153/// Returns true when the info popup was scrolled.
1154bool cmdline_mousescroll(int dir)
1155{
1156  cmdarg_T cap;
1157  oparg_T oa;
1158  CLEAR_FIELD(cap);
1159  clear_oparg(&oa);
1160  cap.oap = &oa;
1161  cap.arg = dir;
1162
1163  switch (dir) {
1164  case MSCR_UP:
1165    cap.cmdchar = K_MOUSEUP; break;
1166  case MSCR_DOWN:
1167    cap.cmdchar = K_MOUSEDOWN; break;
1168  case MSCR_LEFT:
1169    cap.cmdchar = K_MOUSELEFT; break;
1170  case MSCR_RIGHT:
1171    cap.cmdchar = K_MOUSERIGHT; break;
1172  }
1173
1174  if (mouse_row < 0 || mouse_col < 0) {
1175    return false;
1176  }
1177
1178  int grid = mouse_grid;
1179  int row = mouse_row;
1180  int col = mouse_col;
1181
1182  // Only scroll when the mouse is on top of the info popup.
1183  win_T *wp = mouse_find_win_inner(&grid, &row, &col);
1184  if (wp == NULL || wp->w_kind != kWinInfo) {
1185    return false;
1186  }
1187
1188  win_T *old_curwin = curwin;
1189
1190  curwin = wp;
1191  curbuf = wp->w_buffer;
1192  // Call the common mouse scroll function shared with other modes.
1193  do_mousescroll(&cap);
1194  curwin = old_curwin;
1195  curbuf = curwin->w_buffer;
1196
1197  // Cmdline mode doesn't normally call update_screen(), so call it here.
1198  update_screen();
1199  return true;
1200}
1201
1202/// Return true if "c" is a mouse key.
1203bool is_mouse_key(int c)
1204{
1205  return c == K_LEFTMOUSE
1206         || c == K_LEFTMOUSE_NM
1207         || c == K_LEFTDRAG
1208         || c == K_LEFTRELEASE
1209         || c == K_LEFTRELEASE_NM
1210         || c == K_MOUSEMOVE
1211         || c == K_MIDDLEMOUSE
1212         || c == K_MIDDLEDRAG
1213         || c == K_MIDDLERELEASE
1214         || c == K_RIGHTMOUSE
1215         || c == K_RIGHTDRAG
1216         || c == K_RIGHTRELEASE
1217         || c == K_MOUSEDOWN
1218         || c == K_MOUSEUP
1219         || c == K_MOUSELEFT
1220         || c == K_MOUSERIGHT
1221         || c == K_X1MOUSE
1222         || c == K_X1DRAG
1223         || c == K_X1RELEASE
1224         || c == K_X2MOUSE
1225         || c == K_X2DRAG
1226         || c == K_X2RELEASE;
1227}
1228
1229/// @return  true when 'mousemodel' is set to "popup" or "popup_setpos".
1230static bool mouse_model_popup(void)
1231{
1232  return p_mousem[0] == 'p';
1233}
1234
1235static win_T *dragwin = NULL;  ///< window being dragged
1236
1237/// Reset the window being dragged.  To be called when switching tab page.
1238void reset_dragwin(void)
1239{
1240  dragwin = NULL;
1241}
1242
1243/// Move the cursor to the specified row and column on the screen.
1244/// Change current window if necessary. Returns an integer with the
1245/// CURSOR_MOVED bit set if the cursor has moved or unset otherwise.
1246///
1247/// The MOUSE_FOLD_CLOSE bit is set when clicked on the '-' in a fold column.
1248/// The MOUSE_FOLD_OPEN bit is set when clicked on the '+' in a fold column.
1249///
1250/// If flags has MOUSE_FOCUS, then the current window will not be changed, and
1251/// if the mouse is outside the window then the text will scroll, or if the
1252/// mouse was previously on a status line, then the status line may be dragged.
1253///
1254/// If flags has MOUSE_MAY_VIS, then Visual mode will be started before the
1255/// cursor is moved unless the cursor was on a status line or window bar.
1256/// This function returns one of IN_UNKNOWN, IN_BUFFER, IN_STATUS_LINE or
1257/// IN_SEP_LINE depending on where the cursor was clicked.
1258///
1259/// If flags has MOUSE_MAY_STOP_VIS, then Visual mode will be stopped, unless
1260/// the mouse is on the status line or window bar of the same window.
1261///
1262/// If flags has MOUSE_DID_MOVE, nothing is done if the mouse didn't move since
1263/// the last call.
1264///
1265/// If flags has MOUSE_SETPOS, nothing is done, only the current position is
1266/// remembered.
1267///
1268/// @param inclusive  used for inclusive operator, can be NULL
1269/// @param which_button  MOUSE_LEFT, MOUSE_RIGHT, MOUSE_MIDDLE
1270int jump_to_mouse(int flags, bool *inclusive, int which_button)
1271{
1272  static int status_line_offset = 0;        // #lines offset from status line
1273  static int sep_line_offset = 0;           // #cols offset from sep line
1274  static bool on_status_line = false;
1275  static bool on_sep_line = false;
1276  static bool on_winbar = false;
1277  static bool on_statuscol = false;
1278  static int prev_row = -1;
1279  static int prev_col = -1;
1280  static int did_drag = false;          // drag was noticed
1281
1282  int count;
1283  bool first;
1284  int row = mouse_row;
1285  int col = mouse_col;
1286  int grid = mouse_grid;
1287  int fdc = 0;
1288  bool keep_focus = flags & MOUSE_FOCUS;
1289
1290  mouse_past_bottom = false;
1291  mouse_past_eol = false;
1292
1293  if (flags & MOUSE_RELEASED) {
1294    // On button release we may change window focus if positioned on a
1295    // status line and no dragging happened.
1296    if (dragwin != NULL && !did_drag) {
1297      flags &= ~(MOUSE_FOCUS | MOUSE_DID_MOVE);
1298    }
1299    dragwin = NULL;
1300    did_drag = false;
1301  }
1302
1303  if ((flags & MOUSE_DID_MOVE)
1304      && prev_row == mouse_row
1305      && prev_col == mouse_col) {
1306retnomove:
1307    // before moving the cursor for a left click which is NOT in a status
1308    // line, stop Visual mode
1309    if (status_line_offset) {
1310      return IN_STATUS_LINE;
1311    }
1312    if (sep_line_offset) {
1313      return IN_SEP_LINE;
1314    }
1315    if (on_winbar) {
1316      return IN_OTHER_WIN | MOUSE_WINBAR;
1317    }
1318    if (on_statuscol) {
1319      return IN_OTHER_WIN | MOUSE_STATUSCOL;
1320    }
1321    if (flags & MOUSE_MAY_STOP_VIS) {
1322      end_visual_mode();
1323      redraw_curbuf_later(UPD_INVERTED);  // delete the inversion
1324    }
1325    return IN_BUFFER;
1326  }
1327
1328  prev_row = mouse_row;
1329  prev_col = mouse_col;
1330
1331  if (flags & MOUSE_SETPOS) {
1332    goto retnomove;                             // ugly goto...
1333  }
1334
1335  if (row < 0 || col < 0) {                   // check if it makes sense
1336    return IN_UNKNOWN;
1337  }
1338
1339  // find the window where the row is in and adjust "row" and "col" to be
1340  // relative to top-left of the window inner area
1341  win_T *wp = mouse_find_win_inner(&grid, &row, &col);
1342  if (wp == NULL) {
1343    return IN_UNKNOWN;
1344  }
1345
1346  bool below_window = grid == DEFAULT_GRID_HANDLE && row + wp->w_winbar_height >= wp->w_height;
1347  on_status_line = below_window && row + wp->w_winbar_height - wp->w_height + 1 == 1;
1348  on_sep_line = grid == DEFAULT_GRID_HANDLE && col >= wp->w_width && col - wp->w_width + 1 == 1;
1349  on_winbar = row < 0 && row + wp->w_winbar_height >= 0;
1350  on_statuscol = !below_window && !on_status_line && !on_sep_line && !on_winbar
1351                 && *wp->w_p_stc != NUL
1352                 && (wp->w_p_rl
1353                     ? col >= wp->w_view_width - win_col_off(wp)
1354                     : col < win_col_off(wp));
1355
1356  // The rightmost character of the status line might be a vertical
1357  // separator character if there is no connecting window to the right.
1358  if (on_status_line && on_sep_line) {
1359    if (stl_connected(wp)) {
1360      on_sep_line = false;
1361    } else {
1362      on_status_line = false;
1363    }
1364  }
1365
1366  if (keep_focus) {
1367    // If we can't change focus, set the value of row, col and grid back to absolute values
1368    // since the values relative to the window are only used when keep_focus is false
1369    row = mouse_row;
1370    col = mouse_col;
1371    grid = mouse_grid;
1372  }
1373
1374  win_T *old_curwin = curwin;
1375  pos_T old_cursor = curwin->w_cursor;
1376  if (!keep_focus) {
1377    if (on_winbar) {
1378      return IN_OTHER_WIN | MOUSE_WINBAR;
1379    }
1380
1381    if (on_statuscol) {
1382      goto foldclick;
1383    }
1384
1385    fdc = win_fdccol_count(wp);
1386    dragwin = NULL;
1387
1388    // winpos and height may change in win_enter()!
1389    if (below_window) {
1390      // In (or below) status line
1391      status_line_offset = row + wp->w_winbar_height - wp->w_height + 1;
1392      dragwin = wp;
1393    } else {
1394      status_line_offset = 0;
1395    }
1396
1397    if (grid == DEFAULT_GRID_HANDLE && col >= wp->w_width) {
1398      // In separator line
1399      sep_line_offset = col - wp->w_width + 1;
1400      dragwin = wp;
1401    } else {
1402      sep_line_offset = 0;
1403    }
1404
1405    // The rightmost character of the status line might be a vertical
1406    // separator character if there is no connecting window to the right.
1407    if (status_line_offset && sep_line_offset) {
1408      if (stl_connected(wp)) {
1409        sep_line_offset = 0;
1410      } else {
1411        status_line_offset = 0;
1412      }
1413    }
1414
1415    // Before jumping to another buffer, or moving the cursor for a left
1416    // click, stop Visual mode.
1417    if (Visual.active
1418        && (wp->w_buffer != curwin->w_buffer
1419            || (!status_line_offset
1420                && !sep_line_offset
1421                && (wp->w_p_rl
1422                    ? col < wp->w_view_width - fdc
1423                    : col >= fdc)
1424                && (flags & MOUSE_MAY_STOP_VIS)))) {
1425      end_visual_mode();
1426      redraw_curbuf_later(UPD_INVERTED);  // delete the inversion
1427    }
1428    // Only change window focus when not clicking on or dragging the
1429    // status line.  Do change focus when releasing the mouse button
1430    // (MOUSE_FOCUS was set above if we dragged first).
1431    if (dragwin == NULL || (flags & MOUSE_RELEASED)) {
1432      win_enter(wp, true);                      // can make wp invalid!
1433    }
1434    // set topline, to be able to check for double click ourselves
1435    if (curwin != old_curwin) {
1436      set_mouse_topline(curwin);
1437    }
1438    if (status_line_offset) {                       // In (or below) status line
1439      // Don't use start_arrow() if we're in the same window
1440      if (curwin == old_curwin) {
1441        return IN_STATUS_LINE;
1442      }
1443      return IN_STATUS_LINE | CURSOR_MOVED;
1444    }
1445    if (sep_line_offset) {                          // In (or below) status line
1446      // Don't use start_arrow() if we're in the same window
1447      if (curwin == old_curwin) {
1448        return IN_SEP_LINE;
1449      }
1450      return IN_SEP_LINE | CURSOR_MOVED;
1451    }
1452
1453    curwin->w_cursor.lnum = curwin->w_topline;
1454  } else if (status_line_offset) {
1455    if (which_button == MOUSE_LEFT && dragwin != NULL) {
1456      // Drag the status line
1457      count = row - dragwin->w_winrow - dragwin->w_height + 1
1458              - status_line_offset;
1459      win_drag_status_line(dragwin, count);
1460      did_drag |= count;
1461    }
1462    return IN_STATUS_LINE;                      // Cursor didn't move
1463  } else if (sep_line_offset && which_button == MOUSE_LEFT) {
1464    if (dragwin != NULL) {
1465      // Drag the separator column
1466      count = col - dragwin->w_wincol - dragwin->w_width + 1
1467              - sep_line_offset;
1468      win_drag_vsep_line(dragwin, count);
1469      did_drag |= count;
1470    }
1471    return IN_SEP_LINE;                         // Cursor didn't move
1472  } else if (on_status_line && which_button == MOUSE_RIGHT) {
1473    return IN_STATUS_LINE;
1474  } else if (on_winbar && which_button == MOUSE_RIGHT) {
1475    // After a click on the window bar don't start Visual mode.
1476    return IN_OTHER_WIN | MOUSE_WINBAR;
1477  } else if (on_statuscol && which_button == MOUSE_RIGHT) {
1478    // After a click on the status column don't start Visual mode.
1479    return IN_OTHER_WIN | MOUSE_STATUSCOL;
1480  } else {
1481    // keep_window_focus must be true
1482    // before moving the cursor for a left click, stop Visual mode
1483    if (flags & MOUSE_MAY_STOP_VIS) {
1484      end_visual_mode();
1485      redraw_curbuf_later(UPD_INVERTED);  // delete the inversion
1486    }
1487
1488    if (grid == 0) {
1489      row -= curwin->w_grid_alloc.comp_row + curwin->w_grid.row_offset;
1490      col -= curwin->w_grid_alloc.comp_col + curwin->w_grid.col_offset;
1491    } else if (grid != DEFAULT_GRID_HANDLE) {
1492      row -= curwin->w_grid.row_offset;
1493      col -= curwin->w_grid.col_offset;
1494    }
1495
1496    // When clicking beyond the end of the window, scroll the screen.
1497    // Scroll by however many rows outside the window we are.
1498    if (row < 0) {
1499      count = 0;
1500      for (first = true; curwin->w_topline > 1;) {
1501        if (curwin->w_topfill < win_get_fill(curwin, curwin->w_topline)) {
1502          count++;
1503        } else {
1504          count += plines_win(curwin, curwin->w_topline - 1, true);
1505        }
1506        if (!first && count > -row) {
1507          break;
1508        }
1509        first = false;
1510        hasFolding(curwin, curwin->w_topline, &curwin->w_topline, NULL);
1511        if (curwin->w_topfill < win_get_fill(curwin, curwin->w_topline)) {
1512          curwin->w_topfill++;
1513        } else {
1514          curwin->w_topline--;
1515          curwin->w_topfill = 0;
1516        }
1517      }
1518      check_topfill(curwin, false);
1519      curwin->w_valid &=
1520        ~(VALID_WROW|VALID_CROW|VALID_BOTLINE|VALID_BOTLINE_AP);
1521      redraw_later(curwin, UPD_VALID);
1522      row = 0;
1523    } else if (row >= curwin->w_view_height) {
1524      count = 0;
1525      for (first = true; curwin->w_topline < curbuf->b_ml.ml_line_count;) {
1526        if (curwin->w_topfill > 0) {
1527          count++;
1528        } else {
1529          count += plines_win(curwin, curwin->w_topline, true);
1530        }
1531
1532        if (!first && count > row - curwin->w_view_height + 1) {
1533          break;
1534        }
1535        first = false;
1536
1537        if (curwin->w_topfill > 0) {
1538          curwin->w_topfill--;
1539        } else {
1540          if (hasFolding(curwin, curwin->w_topline, NULL, &curwin->w_topline)
1541              && curwin->w_topline == curbuf->b_ml.ml_line_count) {
1542            break;
1543          }
1544          curwin->w_topline++;
1545          curwin->w_topfill = win_get_fill(curwin, curwin->w_topline);
1546        }
1547      }
1548      check_topfill(curwin, false);
1549      redraw_later(curwin, UPD_VALID);
1550      curwin->w_valid &=
1551        ~(VALID_WROW|VALID_CROW|VALID_BOTLINE|VALID_BOTLINE_AP);
1552      row = curwin->w_view_height - 1;
1553    } else if (row == 0) {
1554      // When dragging the mouse, while the text has been scrolled up as
1555      // far as it goes, moving the mouse in the top line should scroll
1556      // the text down (done later when recomputing w_topline).
1557      if (mouse_dragging > 0
1558          && curwin->w_cursor.lnum
1559          == curwin->w_buffer->b_ml.ml_line_count
1560          && curwin->w_cursor.lnum == curwin->w_topline) {
1561        curwin->w_valid &= ~(VALID_TOPLINE);
1562      }
1563    }
1564  }
1565
1566foldclick:;
1567  colnr_T col_from_screen = -1;
1568  int mouse_fold_flags = 0;
1569  mouse_check_grid(&col_from_screen, &mouse_fold_flags);
1570
1571  // compute the position in the buffer line from the posn on the screen
1572  if (mouse_comp_pos(curwin, &row, &col, &curwin->w_cursor.lnum)) {
1573    mouse_past_bottom = true;
1574  }
1575
1576  // Start Visual mode before coladvance(), for when 'sel' != "old"
1577  if ((flags & MOUSE_MAY_VIS) && !Visual.active) {
1578    Visual.start = old_cursor;
1579    Visual.active = true;
1580    Visual.reselect = true;
1581    // if 'selectmode' contains "mouse", start Select mode
1582    may_start_select('o');
1583    setmouse();
1584
1585    if (p_smd && msg_silent == 0) {
1586      redraw_cmdline = true;            // show visual mode later
1587    }
1588  }
1589
1590  if (col_from_screen >= 0) {
1591    col = col_from_screen;
1592  }
1593
1594  curwin->w_curswant = col;
1595  curwin->w_set_curswant = false;       // May still have been true
1596  if (coladvance(curwin, col) == FAIL) {        // Mouse click beyond end of line
1597    if (inclusive != NULL) {
1598      *inclusive = true;
1599    }
1600    mouse_past_eol = true;
1601  } else if (inclusive != NULL) {
1602    *inclusive = false;
1603  }
1604
1605  count = on_statuscol ? (IN_OTHER_WIN|MOUSE_STATUSCOL) : IN_BUFFER;
1606  if (curwin != old_curwin || curwin->w_cursor.lnum != old_cursor.lnum
1607      || curwin->w_cursor.col != old_cursor.col) {
1608    count |= CURSOR_MOVED;              // Cursor has moved
1609  }
1610
1611  count |= mouse_fold_flags;
1612
1613  return count;
1614}
1615
1616/// Make a horizontal scroll to "leftcol".
1617/// @return true if the cursor moved, false otherwise.
1618static bool do_mousescroll_horiz(colnr_T leftcol)
1619{
1620  if (curwin->w_p_wrap) {
1621    return false;  // no horizontal scrolling when wrapping
1622  }
1623  if (curwin->w_leftcol == leftcol) {
1624    return false;  // already there
1625  }
1626
1627  // When the line of the cursor is too short, move the cursor to the
1628  // longest visible line.
1629  if (!virtual_active(curwin)
1630      && leftcol > scroll_line_len(curwin->w_cursor.lnum)) {
1631    curwin->w_cursor.lnum = find_longest_lnum();
1632    curwin->w_cursor.col = 0;
1633  }
1634
1635  return set_leftcol(leftcol);
1636}
1637
1638/// Normal and Visual modes implementation for scrolling in direction
1639/// "cap->arg", which is one of the MSCR_ values.
1640void nv_mousescroll(cmdarg_T *cap)
1641{
1642  win_T *const old_curwin = curwin;
1643
1644  if (mouse_row >= 0 && mouse_col >= 0) {
1645    // Find the window at the mouse pointer coordinates.
1646    // NOTE: Must restore "curwin" to "old_curwin" before returning!
1647    int grid = mouse_grid;
1648    int row = mouse_row;
1649    int col = mouse_col;
1650    curwin = mouse_find_win_inner(&grid, &row, &col);
1651    if (curwin == NULL) {
1652      curwin = old_curwin;
1653      return;
1654    }
1655    curbuf = curwin->w_buffer;
1656  }
1657
1658  // Call the common mouse scroll function shared with other modes.
1659  do_mousescroll(cap);
1660
1661  curwin->w_redr_status = true;
1662  curwin = old_curwin;
1663  curbuf = curwin->w_buffer;
1664}
1665
1666/// Mouse clicks and drags.
1667void nv_mouse(cmdarg_T *cap)
1668{
1669  do_mouse(cap->oap, cap->cmdchar, BACKWARD, cap->count1, 0);
1670}
1671
1672/// Compute the buffer line position from the screen position "rowp" / "colp" in
1673/// window "win".
1674/// Returns true if the position is below the last line.
1675bool mouse_comp_pos(win_T *win, int *rowp, int *colp, linenr_T *lnump)
1676{
1677  int col = *colp;
1678  int row = *rowp;
1679  bool retval = false;
1680  int count;
1681
1682  if (win->w_p_rl) {
1683    col = win->w_view_width - 1 - col;
1684  }
1685
1686  linenr_T lnum = win->w_topline;
1687
1688  while (row > 0) {
1689    // Don't include filler lines in "count"
1690    int filler_lines = lnum == win->w_topline ? win->w_topfill : win_get_fill(win, lnum);
1691    count = plines_win_nofill(win, lnum, false);
1692
1693    if (win->w_skipcol > 0 && lnum == win->w_topline) {
1694      int width1 = win->w_view_width - win_col_off(win);
1695
1696      if (width1 > 0) {
1697        int skip_lines = 0;
1698
1699        // Adjust for 'smoothscroll' clipping the top screen lines.
1700        // A similar formula is used in curs_columns().
1701        if (win->w_skipcol > width1) {
1702          skip_lines = (win->w_skipcol - width1) / (width1 + win_col_off2(win)) + 1;
1703        } else if (win->w_skipcol > 0) {
1704          skip_lines = 1;
1705        }
1706
1707        count -= skip_lines;
1708      }
1709    }
1710
1711    if (count + filler_lines > row) {
1712      break;            // Position is in this buffer line.
1713    }
1714
1715    hasFolding(win, lnum, NULL, &lnum);
1716
1717    if (lnum == win->w_buffer->b_ml.ml_line_count) {
1718      retval = true;
1719      break;                    // past end of file
1720    }
1721    row -= count + filler_lines;
1722    lnum++;
1723  }
1724
1725  int virt_below = 0;
1726  int virt_lines = decor_virt_lines(win, lnum - 1, lnum, &virt_below, NULL, true);
1727  int diff_fill = diff_check_fill(win, lnum);
1728  int skip_fill = lnum == win->w_topline ? virt_lines + diff_fill - win->w_topfill : 0;
1729
1730  // Compute v:virt/lnum as it was when the statuscolmn was drawn. Used to fetch
1731  // the click definition for this row from w_statuscol_click_defs, and so that
1732  // it is available in 'statuscolumn' click handlers.
1733  int virtnum = row - (virt_lines + diff_fill - skip_fill);
1734  if (row < virt_below - skip_fill) {
1735    // Clicking a "below" virtual line should interact with the line above,
1736    // rather than the next line to which it is attached in the decor/draw sense.
1737    lnum--;
1738    int virt_below_prev = 0;
1739    int virt_lines_prev = decor_virt_lines(win, lnum - 1, lnum, &virt_below_prev, NULL, true);
1740    int diff_fill_prev = diff_check_fill(win, lnum - 1);
1741    virtnum = -row - 1 - virt_lines_prev - diff_fill_prev + virt_below_prev;
1742  } else if (row < virt_lines + diff_fill - skip_fill) {
1743    virtnum = -row;
1744  }
1745  set_vim_var_nr(VV_LNUM, lnum);
1746  set_vim_var_nr(VV_VIRTNUM, virtnum);
1747
1748  row -= virt_lines + diff_fill - skip_fill;
1749
1750  // Mouse row reached, adjust lnum for concealed lines.
1751  while (lnum < win->w_buffer->b_ml.ml_line_count
1752         && decor_conceal_line(win, lnum - 1, false)) {
1753    lnum++;
1754    hasFolding(win, lnum, NULL, &lnum);
1755  }
1756
1757  if (!retval) {
1758    // Compute the column without wrapping.
1759    int off = win_col_off(win) - win_col_off2(win);
1760    col = MAX(col, off);
1761    col += row * (win->w_view_width - off);
1762
1763    // Add skip column for the topline.
1764    if (lnum == win->w_topline) {
1765      col += win->w_skipcol;
1766    }
1767  }
1768
1769  if (!win->w_p_wrap) {
1770    col += win->w_leftcol;
1771  }
1772
1773  // skip line number and fold column in front of the line
1774  col -= win_col_off(win);
1775  col = MAX(col, 0);
1776
1777  *colp = col;
1778  *rowp = row;
1779  *lnump = lnum;
1780  return retval;
1781}
1782
1783/// Find the window at "grid" position "*rowp" and "*colp".  The positions are
1784/// updated to become relative to the top-left of the window inner area.
1785///
1786/// @return NULL when something is wrong.
1787win_T *mouse_find_win_inner(int *gridp, int *rowp, int *colp)
1788{
1789  win_T *wp_grid = mouse_find_grid_win(gridp, rowp, colp);
1790  if (wp_grid) {
1791    return wp_grid;
1792  } else if (*gridp > 1) {
1793    return NULL;
1794  }
1795
1796  frame_T *fp = topframe;
1797  *rowp -= firstwin->w_winrow;
1798  while (true) {
1799    if (fp->fr_layout == FR_LEAF) {
1800      break;
1801    }
1802    if (fp->fr_layout == FR_ROW) {
1803      for (fp = fp->fr_child; fp->fr_next != NULL; fp = fp->fr_next) {
1804        if (*colp < fp->fr_width) {
1805          break;
1806        }
1807        *colp -= fp->fr_width;
1808      }
1809    } else {  // fr_layout == FR_COL
1810      for (fp = fp->fr_child; fp->fr_next != NULL; fp = fp->fr_next) {
1811        if (*rowp < fp->fr_height) {
1812          break;
1813        }
1814        *rowp -= fp->fr_height;
1815      }
1816    }
1817  }
1818  // When using a timer that closes a window the window might not actually
1819  // exist.
1820  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
1821    if (wp == fp->fr_win) {
1822      *rowp -= wp->w_winbar_height;
1823      return wp;
1824    }
1825  }
1826  return NULL;
1827}
1828
1829/// Find the window at "grid" position "*rowp" and "*colp".  The positions are
1830/// updated to become relative to the top-left of the window.
1831///
1832/// @return NULL when something is wrong.
1833win_T *mouse_find_win_outer(int *gridp, int *rowp, int *colp)
1834{
1835  win_T *wp = mouse_find_win_inner(gridp, rowp, colp);
1836  if (wp) {
1837    *rowp += wp->w_winrow_off;
1838    *colp += wp->w_wincol_off;
1839  }
1840  return wp;
1841}
1842
1843static win_T *mouse_find_grid_win(int *gridp, int *rowp, int *colp)
1844{
1845  if (*gridp == msg_grid.handle) {
1846    *rowp += msg_grid_pos;
1847    *gridp = DEFAULT_GRID_HANDLE;
1848  } else if (*gridp > 1) {
1849    win_T *wp = get_win_by_grid_handle(*gridp);
1850    if (wp && wp->w_grid_alloc.chars
1851        && !(wp->w_floating && !wp->w_config.mouse)) {
1852      *rowp = MIN(*rowp - wp->w_grid.row_offset, wp->w_view_height - 1);
1853      *colp = MIN(*colp - wp->w_grid.col_offset, wp->w_view_width - 1);
1854      return wp;
1855    }
1856  } else if (*gridp == 0) {
1857    ScreenGrid *grid = ui_comp_mouse_focus(*rowp, *colp);
1858    if (grid == &pum_grid) {
1859      *gridp = grid->handle;
1860      *rowp -= grid->comp_row;
1861      *colp -= grid->comp_col;
1862      // The popup menu doesn't have a window, so return NULL
1863      return NULL;
1864    } else {
1865      FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
1866        if (&wp->w_grid_alloc != grid) {
1867          continue;
1868        }
1869        *gridp = grid->handle;
1870        *rowp -= wp->w_winrow + wp->w_grid.row_offset;
1871        *colp -= wp->w_wincol + wp->w_grid.col_offset;
1872        return wp;
1873      }
1874    }
1875
1876    // No grid found, return the default grid. With multigrid this happens for split separators for
1877    // example.
1878    *gridp = DEFAULT_GRID_HANDLE;
1879  }
1880  return NULL;
1881}
1882
1883/// Convert a virtual (screen) column to a character column.
1884/// The first column is zero.
1885colnr_T vcol2col(win_T *wp, linenr_T lnum, colnr_T vcol, colnr_T *coladdp)
1886  FUNC_ATTR_NONNULL_ARG(1) FUNC_ATTR_WARN_UNUSED_RESULT
1887{
1888  // try to advance to the specified column
1889  char *line = ml_get_buf(wp->w_buffer, lnum);
1890  CharsizeArg csarg;
1891  CSType cstype = init_charsize_arg(&csarg, wp, lnum, line);
1892  StrCharInfo ci = utf_ptr2StrCharInfo(line);
1893  int cur_vcol = 0;
1894  while (cur_vcol < vcol && *ci.ptr != NUL) {
1895    ClusterInfo cli = utf_ClusterInfo(ci);
1896    int next_vcol = cur_vcol + win_charsize(cstype, cur_vcol, ci.ptr, ci.chr.value, &csarg,
1897                                            cli.cells).width;
1898    if (next_vcol > vcol) {
1899      break;
1900    }
1901    cur_vcol = next_vcol;
1902    ci = cli.next;
1903  }
1904
1905  if (coladdp != NULL) {
1906    *coladdp = vcol - cur_vcol;
1907  }
1908  return (colnr_T)(ci.ptr - line);
1909}
1910
1911/// Set UI mouse depending on current mode and 'mouse'.
1912///
1913/// Emits mouse_on/mouse_off UI event (unless 'mouse' is empty).
1914void setmouse(void)
1915{
1916  ui_cursor_shape();
1917  ui_check_mouse();
1918}
1919
1920// Set orig_topline.  Used when jumping to another window, so that a double
1921// click still works.
1922static void set_mouse_topline(win_T *wp)
1923{
1924  orig_topline = wp->w_topline;
1925  orig_topfill = wp->w_topfill;
1926}
1927
1928/// Return length of line "lnum" for horizontal scrolling.
1929static colnr_T scroll_line_len(linenr_T lnum)
1930{
1931  colnr_T col = 0;
1932  char *line = ml_get(lnum);
1933  if (*line != NUL) {
1934    while (true) {
1935      int numchar = win_chartabsize(curwin, line, col);
1936      MB_PTR_ADV(line);
1937      if (*line == NUL) {    // don't count the last character
1938        break;
1939      }
1940      col += numchar;
1941    }
1942  }
1943  return col;
1944}
1945
1946/// Find longest visible line number.
1947static linenr_T find_longest_lnum(void)
1948{
1949  linenr_T ret = 0;
1950
1951  // Calculate maximum for horizontal scrollbar.  Check for reasonable
1952  // line numbers, topline and botline can be invalid when displaying is
1953  // postponed.
1954  if (curwin->w_topline <= curwin->w_cursor.lnum
1955      && curwin->w_botline > curwin->w_cursor.lnum
1956      && curwin->w_botline <= curbuf->b_ml.ml_line_count + 1) {
1957    colnr_T max = 0;
1958
1959    // Use maximum of all visible lines.  Remember the lnum of the
1960    // longest line, closest to the cursor line.  Used when scrolling
1961    // below.
1962    for (linenr_T lnum = curwin->w_topline; lnum < curwin->w_botline; lnum++) {
1963      colnr_T len = scroll_line_len(lnum);
1964      if (len > max) {
1965        max = len;
1966        ret = lnum;
1967      } else if (len == max
1968                 && abs(lnum - curwin->w_cursor.lnum)
1969                 < abs(ret - curwin->w_cursor.lnum)) {
1970        ret = lnum;
1971      }
1972    }
1973  } else {
1974    // Use cursor line only.
1975    ret = curwin->w_cursor.lnum;
1976  }
1977
1978  return ret;
1979}
1980
1981/// Check clicked cell on its grid
1982static void mouse_check_grid(colnr_T *vcolp, int *flagsp)
1983  FUNC_ATTR_NONNULL_ALL
1984{
1985  int click_grid = mouse_grid;
1986  int click_row = mouse_row;
1987  int click_col = mouse_col;
1988
1989  // XXX: this doesn't change click_grid if it is 1, even with multigrid
1990  if (mouse_find_win_inner(&click_grid, &click_row, &click_col) != curwin
1991      // Only use vcols[] after the window was redrawn.  Mainly matters
1992      // for tests, a user would not click before redrawing.
1993      || curwin->w_redr_type != 0) {
1994    return;
1995  }
1996  int start_row = 0;
1997  int start_col = 0;
1998  ScreenGrid *gp = grid_adjust(&curwin->w_grid, &start_row, &start_col);
1999  if (gp->handle != click_grid || gp->chars == NULL) {
2000    return;
2001  }
2002  click_row += start_row;
2003  click_col += start_col;
2004  if (click_row < 0 || click_row >= gp->rows
2005      || click_col < 0 || click_col >= gp->cols) {
2006    return;
2007  }
2008
2009  const size_t off = gp->line_offset[click_row] + (size_t)click_col;
2010  colnr_T col_from_screen = gp->vcols[off];
2011
2012  if (col_from_screen >= 0) {
2013    // Use the virtual column from vcols[], it is accurate also after
2014    // concealed characters.
2015    *vcolp = col_from_screen;
2016  }
2017
2018  if (col_from_screen == -2) {
2019    *flagsp |= MOUSE_FOLD_OPEN;
2020  } else if (col_from_screen == -3) {
2021    *flagsp |= MOUSE_FOLD_CLOSE;
2022  }
2023}
2024
2025/// "getmousepos()" function
2026void f_getmousepos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2027{
2028  int row = mouse_row;
2029  int col = mouse_col;
2030  int grid = mouse_grid;
2031  varnumber_T winid = 0;
2032  varnumber_T winrow = 0;
2033  varnumber_T wincol = 0;
2034  linenr_T lnum = 0;
2035  varnumber_T column = 0;
2036  colnr_T coladd = 0;
2037
2038  tv_dict_alloc_ret(rettv);
2039  dict_T *d = rettv->vval.v_dict;
2040
2041  tv_dict_add_nr(d, S_LEN("screenrow"), (varnumber_T)mouse_row + 1);
2042  tv_dict_add_nr(d, S_LEN("screencol"), (varnumber_T)mouse_col + 1);
2043
2044  win_T *wp = mouse_find_win_inner(&grid, &row, &col);
2045  if (wp != NULL) {
2046    int height = wp->w_height + wp->w_hsep_height + wp->w_status_height;
2047    // The height is adjusted by 1 when there is a bottom border. This is not
2048    // necessary for a top border since `row` starts at -1 in that case.
2049    if (row < height + wp->w_border_adj[2]) {
2050      winid = wp->handle;
2051      winrow = row + 1 + wp->w_winrow_off;  // Adjust by 1 for top border
2052      wincol = col + 1 + wp->w_wincol_off;  // Adjust by 1 for left border
2053      if (row >= 0 && row < wp->w_height && col >= 0 && col < wp->w_width) {
2054        mouse_comp_pos(wp, &row, &col, &lnum);
2055        col = vcol2col(wp, lnum, col, &coladd);
2056        column = col + 1;
2057      }
2058    }
2059  }
2060  tv_dict_add_nr(d, S_LEN("winid"), winid);
2061  tv_dict_add_nr(d, S_LEN("winrow"), winrow);
2062  tv_dict_add_nr(d, S_LEN("wincol"), wincol);
2063  tv_dict_add_nr(d, S_LEN("line"), (varnumber_T)lnum);
2064  tv_dict_add_nr(d, S_LEN("column"), column);
2065  tv_dict_add_nr(d, S_LEN("coladd"), coladd);
2066}