robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// insert.c: functions for Insert mode 2 3#include <assert.h> 4#include <ctype.h> 5#include <inttypes.h> 6#include <stdbool.h> 7#include <stddef.h> 8#include <string.h> 9#include <uv.h> 10 11#include "klib/kvec.h" 12#include "nvim/api/private/defs.h" 13#include "nvim/ascii_defs.h" 14#include "nvim/autocmd.h" 15#include "nvim/autocmd_defs.h" 16#include "nvim/buffer.h" 17#include "nvim/buffer_defs.h" 18#include "nvim/change.h" 19#include "nvim/charset.h" 20#include "nvim/context.h" 21#include "nvim/cursor.h" 22#include "nvim/decoration.h" 23#include "nvim/digraph.h" 24#include "nvim/drawscreen.h" 25#include "nvim/errors.h" 26#include "nvim/eval/buffer.h" 27#include "nvim/eval/typval_defs.h" 28#include "nvim/eval/vars.h" 29#include "nvim/ex_cmds_defs.h" 30#include "nvim/ex_docmd.h" 31#include "nvim/ex_getln.h" 32#include "nvim/extmark.h" 33#include "nvim/extmark_defs.h" 34#include "nvim/fileio.h" 35#include "nvim/fold.h" 36#include "nvim/gettext_defs.h" 37#include "nvim/globals.h" 38#include "nvim/grid.h" 39#include "nvim/grid_defs.h" 40#include "nvim/highlight.h" 41#include "nvim/highlight_defs.h" 42#include "nvim/highlight_group.h" 43#include "nvim/indent.h" 44#include "nvim/indent_c.h" 45#include "nvim/input.h" 46#include "nvim/insert.h" 47#include "nvim/insexpand.h" 48#include "nvim/keycodes.h" 49#include "nvim/macros_defs.h" 50#include "nvim/mapping.h" 51#include "nvim/mark.h" 52#include "nvim/mark_defs.h" 53#include "nvim/marktree_defs.h" 54#include "nvim/mbyte.h" 55#include "nvim/mbyte_defs.h" 56#include "nvim/mcursor.h" 57#include "nvim/memline.h" 58#include "nvim/memline_defs.h" 59#include "nvim/memory.h" 60#include "nvim/message.h" 61#include "nvim/mouse.h" 62#include "nvim/move.h" 63#include "nvim/normal.h" 64#include "nvim/normal_defs.h" 65#include "nvim/ops.h" 66#include "nvim/option.h" 67#include "nvim/option_vars.h" 68#include "nvim/os/input.h" 69#include "nvim/plines.h" 70#include "nvim/popupmenu.h" 71#include "nvim/pos_defs.h" 72#include "nvim/register.h" 73#include "nvim/search.h" 74#include "nvim/state.h" 75#include "nvim/state_defs.h" 76#include "nvim/strings.h" 77#include "nvim/syntax.h" 78#include "nvim/terminal.h" 79#include "nvim/textformat.h" 80#include "nvim/textobject.h" 81#include "nvim/types_defs.h" 82#include "nvim/ui.h" 83#include "nvim/ui_defs.h" 84#include "nvim/undo.h" 85#include "nvim/vim_defs.h" 86#include "nvim/window.h" 87 88typedef struct { 89VimState state ; 90cmdarg_T * ca ; 91int mincol ; 92int cmdchar ; 93int cmdchar_todo ;// cmdchar to handle once in init_prompt 94bool ins_just_started ; 95int startln ; 96int count ; 97int c ; 98int lastc ; 99int i ; 100bool did_backspace ;// previous char was backspace 101bool line_is_white ;// line is empty before insert 102linenr_T old_topline ;// topline before insertion 103int old_topfill ; 104int inserted_space ;// just inserted a space 105int replaceState ; 106int did_restart_edit ;// remember if insert mode was restarted 107// after a ctrl+o 108bool nomove ; 109}InsertState ; 110 111#include "insert.c.generated.h" 112enum { 113BACKSPACE_CHAR = 1 , 114BACKSPACE_WORD = 2 , 115BACKSPACE_WORD_NOT_SPACE = 3 , 116BACKSPACE_LINE = 4 , 117}; 118 119/// Set when doing something for completion that may call edit() recursively, 120/// which is not allowed. 121static bool compl_busy = false; 122 123/// the text of the previous insert, K_SPECIAL is escaped 124static String last_insert = STRING_INIT ; 125static int last_insert_skip ;// nr of chars in front of previous insert 126 127static kvec_t (char )replace_stack = KV_INITIAL_VALUE ; 128 129// With 'autocompletedelay' set, arm the delay and let the main loop fire 130// Insert-mode autocommands; the popup is shown later on K_COMPLETE_DELAY. 131// Otherwise trigger completion right away. 132#define TRIGGER_AUTOCOMPLETE () \ 133 do { \ 134 mc_ins_cascade();/* Multicursor: replay pending keys, since compl refused edit(). #41605 */ \ 135redraw_later (curwin ,UPD_VALID ); \ 136update_screen ();/* Show char deletion immediately */ \ 137ui_flush (); \ 138ins_compl_enable_autocomplete (); \ 139ins_compl_arm_autostart (); \ 140if (!ins_compl_arm_autocomplete_delay ()) { \ 141insert_do_complete (s ); \ 142break ; \ 143 } \ 144 }while (0 ) 145 146#define MAY_TRIGGER_AUTOCOMPLETE (c ) \ 147 do { \ 148 if (ins_compl_has_autocomplete() && !char_avail() && curwin->w_cursor.col > 0) { \ 149 (c) = char_before_cursor(); \ 150 if (vim_isprintc(c)) { \ 151 TRIGGER_AUTOCOMPLETE(); \ 152 } \ 153 } \ 154 } while (0) 155 156static void insert_enter (InsertState * s ) 157{ 158s -> did_backspace = true; 159s -> old_topfill = -1 ; 160s -> replaceState = MODE_REPLACE ; 161s -> cmdchar_todo = s -> cmdchar ; 162s -> ins_just_started = true; 163// Remember whether editing was restarted after CTRL-O 164Ins .did_restart_edit = restart_edit ; 165// sleep before redrawing, needed for "CTRL-O :" that results in an 166// error message 167msg_check_for_delay (true); 168// set Ins.start_orig to Ins.start 169Ins .update_start_orig = true; 170 171ins_compl_clear ();// clear stuff for CTRL-X mode 172 173// Trigger InsertEnter autocommands. Do not do this for "r<CR>" or "grx". 174if (s -> cmdchar != 'r' && s -> cmdchar != 'v' ) { 175pos_T save_cursor = curwin -> w_cursor ; 176 177const char * const ptr = s -> cmdchar == 'R' ?"r" :s -> cmdchar == 'V' ?"v" :"i" ; 178set_vim_var_string (VV_INSERTMODE ,ptr ,1 ); 179set_vim_var_string (VV_CHAR ,NULL ,-1 ); 180ins_apply_autocmds (EVENT_INSERTENTER ); 181 182// Check for changed highlighting, e.g. for ModeMsg. 183if (need_highlight_changed ) { 184highlight_changed (); 185 } 186 187// Make sure the cursor didn't move. Do call check_cursor_col() in 188// case the text was modified. Since Insert mode was not started yet 189// a call to check_cursor_col() may move the cursor, especially with 190// the "A" command, thus set State to avoid that. Also check that the 191// line number is still valid (lines may have been deleted). 192// Do not restore if v:char was set to a non-empty string. 193if (!equalpos (curwin -> w_cursor ,save_cursor ) 194&& * get_vim_var_str (VV_CHAR )== NUL 195&& save_cursor .lnum <=curbuf -> b_ml .ml_line_count ) { 196int save_state = State ; 197 198curwin -> w_cursor = save_cursor ; 199State = MODE_INSERT ; 200check_cursor_col (curwin ); 201State = save_state ; 202 } 203 } 204 205// When doing a paste with the middle mouse button, Ins.start is set to 206// where the paste started. 207if (where_paste_started .lnum != 0 ) { 208Ins .start = where_paste_started ; 209 }else { 210Ins .start = curwin -> w_cursor ; 211if (s -> startln ) { 212Ins .start .col = 0 ; 213 } 214 } 215 216Ins .start_textlen = linetabsize_str (get_cursor_line_ptr ()); 217Ins .start_blank_vcol = MAXCOL ; 218 219if (!Ins .did_ai ) { 220Ins .ai_col = 0 ; 221 } 222 223if (s -> cmdchar != NUL && restart_edit == 0 ) { 224if (s -> cmdchar == 'V' || s -> cmdchar == 'v' ) { 225// "gR" or "gr" command 226prep_redo (false, false, (CmdSpec ){ .count = s -> count , .cmd = 'g' , 227 .cmd2 = (s -> cmdchar == 'v' ) ?'r' :'R' }); 228 }else { 229prep_redo (false, false, (CmdSpec ){ .count = s -> count , .cmd = s -> cmdchar , 230 .cmd2 = (s -> cmdchar == 'g' ) ?'I' :NUL }); 231if (s -> cmdchar == 'r' ) {// "r<CR>" command 232s -> count = 1 ;// insert only one <CR> 233 } 234 } 235 } 236 237if (s -> cmdchar == 'R' ) { 238State = MODE_REPLACE ; 239 }else if (s -> cmdchar == 'V' || s -> cmdchar == 'v' ) { 240State = MODE_VREPLACE ; 241s -> replaceState = MODE_VREPLACE ; 242orig_line_count = curbuf -> b_ml .ml_line_count ; 243vr_lines_changed = 1 ; 244 }else { 245State = MODE_INSERT ; 246 } 247 248may_trigger_modechanged (); 249Ins .stop_insert_mode = false; 250 251// need to position cursor again when on a TAB and 252// when on a char with inline virtual text 253if (gchar_cursor ()== TAB || buf_meta_total (curbuf ,kMTMetaInline )> 0 ) { 254curwin -> w_valid &= ~(VALID_WROW |VALID_WCOL |VALID_VIRTCOL ); 255 } 256 257// Enable langmap or IME, indicated by 'iminsert'. 258// Note that IME may enabled/disabled without us noticing here, thus the 259// 'iminsert' value may not reflect what is actually used. It is updated 260// when hitting <Esc>. 261if (curbuf -> b_p_iminsert == B_IMODE_LMAP ) { 262State |=MODE_LANGMAP ; 263 } 264 265setmouse (); 266clear_showcmd (); 267// there is no reverse replace mode 268Ins .revins_on = (State == MODE_INSERT && p_ri ); 269if (Ins .revins_on ) { 270undisplay_dollar (); 271 } 272Ins .revins_chars = 0 ; 273Ins .revins_legal = 0 ; 274Ins .revins_scol = -1 ; 275 276// Handle restarting Insert mode. 277// Don't do this for "CTRL-O ." (repeat an insert): we get here with 278// restart_edit non-zero, and something in the stuff buffer. 279if (restart_edit != 0 && stuff_empty ()) { 280// After a paste we consider text typed to be part of the insert for 281// the pasted text. You can backspace over the pasted text too. 282Ins .moved = where_paste_started .lnum == 0 ?kInsJump :kInsNone ; 283restart_edit = 0 ; 284 285// If the cursor was after the end-of-line before the CTRL-O and it is 286// now at the end-of-line, put it after the end-of-line (this is not 287// correct in very rare cases). 288// Also do this if curswant is greater than the current virtual 289// column. Eg after "^O$" or "^O80|". 290validate_virtcol (curwin ); 291update_curswant (); 292const char * ptr ; 293if (((ins_at_eol && curwin -> w_cursor .lnum == Ins .o_lnum ) 294|| curwin -> w_curswant > curwin -> w_virtcol ) 295&& * (ptr = get_cursor_line_ptr ()+ curwin -> w_cursor .col )!= NUL ) { 296if (ptr [1 ]== NUL ) { 297curwin -> w_cursor .col ++ ; 298 }else { 299s -> i = utfc_ptr2len (ptr ); 300if (ptr [s -> i ]== NUL ) { 301curwin -> w_cursor .col += s -> i ; 302 } 303 } 304 } 305ins_at_eol = false; 306 }else { 307Ins .moved = kInsNone ; 308 } 309 310// we are in insert mode now, don't need to start it anymore 311need_start_insertmode = false; 312 313// Need to save the line for undo before inserting the first char. 314Ins .need_undo = true; 315 316where_paste_started .lnum = 0 ; 317Ins .can_cindent = true; 318// The cursor line is not in a closed fold, unless restarting. 319if (Ins .did_restart_edit == 0 ) { 320foldOpenCursor (); 321 } 322 323// If 'showmode' is set, show the current (insert/replace/..) mode. 324// A warning message for changing a readonly file is given here, before 325// actually changing anything. It's put after the mode, if any. 326s -> i = 0 ; 327if (p_smd && msg_silent == 0 ) { 328s -> i = showmode (); 329 } 330 331if (Ins .did_restart_edit == 0 ) { 332change_warning (curbuf ,s -> i == 0 ?0 :s -> i + 1 ); 333 } 334 335ui_cursor_shape ();// may show different cursor shape 336do_digraph (-1 );// clear digraphs 337 338// Get the current length of the redo buffer, those characters have to be 339// skipped if we want to get to the inserted characters. 340String redo = redo_keys (NULL ); 341Ins .new_insert_skip = (int )redo .size ; 342if (redo .data != NULL ) { 343xfree (redo .data ); 344 } 345 346old_indent = 0 ; 347 348do { 349state_enter (& s -> state ); 350// If s->count != 0, `ins_esc` will prepare the redo buffer for reprocessing 351// and return false, causing `state_enter` to be called again. 352 }while (!ins_esc (& s -> count ,s -> cmdchar ,s -> nomove )); 353 354// Drop a pending autocomplete so it does not outlive Insert mode. 355ins_compl_clear_autocomplete_delay (); 356// Always update Ins.o_lnum, so that a "CTRL-O ." that adds a line 357// still puts the cursor back after the inserted text. 358if (ins_at_eol ) { 359Ins .o_lnum = curwin -> w_cursor .lnum ; 360 } 361 362pum_check_clear (); 363 364foldUpdateAfterInsert (); 365// When CTRL-C was typed got_int will be set, with the result 366// that the autocommands won't be executed. When mapped got_int 367// is not set, but let's keep the behavior the same. 368if (s -> cmdchar != 'r' && s -> cmdchar != 'v' && s -> c != Ctrl_C ) { 369ins_apply_autocmds (EVENT_INSERTLEAVE ); 370 } 371did_cursorhold = false; 372 373// ins_redraw() triggers TextChangedI only when no characters 374// are in the typeahead buffer, so reset curbuf->b_last_changedtick 375// if the TextChangedI was not blocked by char_avail() (e.g. using :norm!) 376// and the TextChangedI autocommand has been triggered. 377if (!char_avail ()&& curbuf -> b_last_changedtick_i == buf_get_changedtick (curbuf )) { 378curbuf -> b_last_changedtick = buf_get_changedtick (curbuf ); 379 } 380} 381 382static int insert_check (VimState * state ) 383{ 384InsertState * s = (InsertState * )state ; 385 386// Multicursor: insert-cascade, before entry ("A"/"o"/"cw"/…), and after every executed key. 387mc_ins_cascade (); 388 389if (!Ins .revins_legal ) { 390Ins .revins_scol = -1 ;// reset on illegal motions 391 }else { 392Ins .revins_legal = 0 ; 393 } 394 395if (Ins .moved != kInsNone ) {// don't repeat insert when arrow key used 396s -> count = 0 ; 397 } 398 399if (Ins .update_start_orig ) { 400Ins .start_orig = Ins .start ; 401 } 402 403if (curbuf -> terminal && !Ins .stop_insert_mode ) { 404// Exit Insert mode and go to Terminal mode. 405Ins .stop_insert_mode = true; 406restart_edit = 'I' ; 407stuffcharReadbuff (K_NOP ); 408 } 409 410if (Ins .stop_insert_mode && !ins_compl_active ()) { 411// ":stopinsert" used 412s -> count = 0 ; 413return 0 ;// exit insert mode 414 } 415 416// set curwin->w_curswant for next K_DOWN or K_UP 417if (Ins .moved == kInsNone ) { 418curwin -> w_set_curswant = true; 419 } 420 421// If there is no typeahead may check for timestamps (e.g., for when a 422// menu invoked a shell command). 423if (stuff_empty ()) { 424did_check_timestamps = false; 425if (need_check_timestamps ) { 426check_timestamps (false); 427 } 428 } 429 430// When emsg() was called msg_scroll will have been set. 431msg_scroll = false; 432 433// Open fold at the cursor line, according to 'foldopen'. 434if (fdo_flags & kOptFdoFlagInsert ) { 435foldOpenCursor (); 436 } 437 438// Close folds where the cursor isn't, according to 'foldclose' 439if (!char_avail ()) { 440foldCheckClose (); 441 } 442 443if (bt_prompt (curbuf )) { 444init_prompt (s -> cmdchar_todo ); 445s -> cmdchar_todo = NUL ; 446 } 447 448// If we inserted a character at the last position of the last line in the 449// window, scroll the window one line up. This avoids an extra redraw. This 450// is detected when the cursor column is smaller after inserting something. 451// Don't do this when the topline changed already, it has already been 452// adjusted (by insertchar() calling open_line())). 453// Also don't do this when 'smoothscroll' is set, as the window should then 454// be scrolled by screen lines. 455if (curbuf -> b_mod_set 456&& curwin -> w_p_wrap 457&& !curwin -> w_p_sms 458&& !s -> did_backspace 459&& curwin -> w_topline == s -> old_topline 460&& curwin -> w_topfill == s -> old_topfill 461&& s -> count <=1 ) { 462s -> mincol = curwin -> w_wcol ; 463validate_cursor_col (curwin ); 464 465if (curwin -> w_wcol < s -> mincol - tabstop_at (get_nolist_virtcol (), 466curbuf -> b_p_ts , 467curbuf -> b_p_vts_array , 468 false) 469&& curwin -> w_wrow == curwin -> w_view_height - 1 - get_scrolloff_value (curwin ) 470&& (curwin -> w_cursor .lnum != curwin -> w_topline 471|| curwin -> w_topfill > 0 )) { 472if (curwin -> w_topfill > 0 ) { 473curwin -> w_topfill -- ; 474 }else if (hasFolding (curwin ,curwin -> w_topline ,NULL ,& s -> old_topline )) { 475set_topline (curwin ,s -> old_topline + 1 ); 476 }else { 477set_topline (curwin ,curwin -> w_topline + 1 ); 478 } 479 } 480 } 481 482// May need to adjust w_topline to show the cursor. 483if (s -> count <=1 ) { 484update_topline (curwin ); 485 } 486 487s -> did_backspace = false; 488 489if (s -> count <=1 ) { 490validate_cursor (curwin );// may set must_redraw 491 } 492 493// Redraw the display when no characters are waiting. 494// Also shows mode, ruler and positions cursor. 495ins_redraw (true); 496 497if (curwin -> w_p_scb ) { 498do_check_scrollbind (true); 499 } 500 501if (curwin -> w_p_crb ) { 502do_check_cursorbind (); 503 } 504 505if (s -> count <=1 ) { 506update_curswant (); 507 } 508s -> old_topline = curwin -> w_topline ; 509s -> old_topfill = curwin -> w_topfill ; 510 511if (s -> c != K_EVENT && s -> c != K_COMPLETE_DELAY ) { 512s -> lastc = s -> c ;// remember the previous char for CTRL-D 513 } 514 515// After using CTRL-G U the next cursor key will not break undo. 516if (Ins .dont_sync_undo == kNone ) { 517Ins .dont_sync_undo = kTrue ; 518 }else { 519Ins .dont_sync_undo = kFalse ; 520 } 521 522// Trigger autocomplete when entering Insert mode, either directly 523// or via change commands like 'ciw', 'cw', etc., before the first 524// character is typed. 525if (s -> ins_just_started ) { 526s -> ins_just_started = false; 527if (ins_compl_has_autocomplete ()&& !char_avail ()&& curwin -> w_cursor .col > 0 ) { 528s -> c = char_before_cursor (); 529if (vim_isprintc (s -> c )) { 530ins_compl_enable_autocomplete (); 531ins_compl_arm_autostart (); 532ins_compl_init_get_longest (); 533// Defer until the delay expires (K_COMPLETE_DELAY), or 534// trigger now when no delay is in effect. 535if (!ins_compl_arm_autocomplete_delay ()) { 536insert_do_complete (s ); 537insert_handle_key_post (s ); 538return 1 ; 539 } 540 } 541 } 542 } 543 544return 1 ; 545} 546 547static int insert_execute (VimState * state ,int key ) 548{ 549InsertState * const s = (InsertState * )state ; 550if (Ins .stop_insert_mode ) { 551// Insert mode ended, possibly from a callback. 552if (key != K_IGNORE && key != K_NOP ) { 553vungetc (key ); 554 } 555s -> count = 0 ; 556s -> nomove = true; 557ins_compl_prep (ESC ); 558return 0 ; 559 } 560 561if (key == K_IGNORE || key == K_NOP ) { 562return -1 ;// get another key 563 } 564s -> c = key ; 565 566// Don't want K_EVENT with cursorhold for the second key, e.g., after CTRL-V. 567if (key != K_EVENT ) { 568did_cursorhold = true; 569 } 570if (key != K_EVENT && key != K_COMPLETE_DELAY ) { 571// Don't want delayed autocompletion from the previous key either. 572ins_compl_clear_autocomplete_delay (); 573ins_compl_disarm_autostart (); 574// A completion already on screen goes on being what it was. 575if (!ins_compl_active ()) { 576ins_compl_disable_autocomplete (); 577 } 578 } 579 580// Special handling of keys while the popup menu is visible or wanted 581// and the cursor is still in the completed word. Only when there is 582// a match, skip this when no matches were found. 583if (ins_compl_active ()&& curwin -> w_cursor .col >=ins_compl_col () 584&& ins_compl_has_shown_match ()&& pum_wanted ()) { 585// BS: Delete one character from "compl_leader". 586if ((s -> c == K_BS || s -> c == Ctrl_H ) 587&& curwin -> w_cursor .col > ins_compl_col () 588&& (s -> c = ins_compl_bs ())== NUL ) { 589return 1 ;// continue 590 } 591 592// When no match was selected or it was edited. 593if (!ins_compl_used_match ()) { 594// CTRL-L: Add one character from the current match to 595// "compl_leader". Except when at the original match and 596// there is nothing to add, CTRL-L works like CTRL-P then. 597if (s -> c == Ctrl_L 598&& (!ctrl_x_mode_line_or_eval () 599|| ins_compl_long_shown_match ())) { 600ins_compl_addfrommatch (); 601return 1 ;// continue 602 } 603 604const bool is_commit = ins_compl_commit_char (s -> c ); 605// A non-white character that fits in with the current 606// completion: Add to "compl_leader". 607if (!is_commit && ins_compl_accept_char (s -> c )) { 608// Trigger InsertCharPre. 609char * str = do_insert_char_pre (s -> c ); 610 611if (str != NULL ) { 612for (char * p = str ;* p != NUL ;MB_PTR_ADV (p )) { 613ins_compl_addleader (utf_ptr2char (p )); 614 } 615xfree (str ); 616 }else { 617ins_compl_addleader (s -> c ); 618 } 619return 1 ;// continue 620 } 621 622// Pressing CTRL-Y selects the current match. When 623// compl_enter_selects is set the Enter key does the same. 624if ((s -> c == Ctrl_Y || is_commit 625|| (ins_compl_enter_selects () 626&& (s -> c == CAR || s -> c == K_KENTER || s -> c == NL ))) 627&& stop_arrow ()== OK ) { 628ins_compl_delete (false); 629if (ins_compl_preinsert_longest ()&& !ins_compl_is_match_selected ()) { 630ins_compl_insert (false, true); 631ins_compl_init_get_longest (); 632return 1 ;// continue 633 }else { 634ins_compl_insert (false, false); 635 } 636 }else if (ascii_iswhite_nl_or_nul (s -> c )&& ins_compl_preinsert_effect ()) { 637// Delete preinserted text when typing special chars 638ins_compl_delete (false); 639 } 640 } 641 } 642 643// Prepare for or stop CTRL-X mode. This doesn't do completion, but it does 644// fix up the text when finishing completion. 645ins_compl_init_get_longest (); 646if (ins_compl_prep (s -> c )) { 647return 1 ;// continue 648 } 649 650// CTRL-\ CTRL-N goes to Normal mode, 651// CTRL-\ CTRL-O is like CTRL-O but without moving the cursor 652if (s -> c == Ctrl_BSL ) { 653// may need to redraw when no more chars available now 654ins_redraw (false); 655no_mapping ++ ; 656allow_keys ++ ; 657s -> c = plain_vgetc (); 658no_mapping -- ; 659allow_keys -- ; 660if (s -> c != Ctrl_N && s -> c != Ctrl_G && s -> c != Ctrl_O ) { 661// it's something else 662vungetc (s -> c ); 663s -> c = Ctrl_BSL ; 664 }else { 665if (s -> c == Ctrl_O ) { 666ins_ctrl_o (); 667ins_at_eol = false;// cursor keeps its column 668s -> nomove = true; 669 } 670s -> count = 0 ; 671return 0 ; 672 } 673 } 674 675if (s -> c != K_EVENT ) { 676s -> c = do_digraph (s -> c ); 677 } 678 679if ((s -> c == Ctrl_V || s -> c == Ctrl_Q )&& ctrl_x_mode_cmdline ()) { 680insert_do_complete (s ); 681insert_handle_key_post (s ); 682return 1 ; 683 } 684 685if (s -> c == Ctrl_V || s -> c == Ctrl_Q ) { 686ins_ctrl_v (); 687s -> c = Ctrl_V ;// pretend CTRL-V is last typed character 688return 1 ;// continue 689 } 690 691if (cindent_on ()&& ctrl_x_mode_none ()) { 692s -> line_is_white = inindent (0 ); 693// A key name preceded by a bang means this key is not to be 694// inserted. Skip ahead to the re-indenting below. 695if (in_cinkeys (s -> c ,'!' ,s -> line_is_white ) 696&& stop_arrow ()== OK ) { 697do_c_expr_indent (); 698return 1 ;// continue 699 } 700// A key name preceded by a star means that indenting has to be 701// done before inserting the key. 702if (Ins .can_cindent && in_cinkeys (s -> c ,'*' ,s -> line_is_white ) 703&& stop_arrow ()== OK ) { 704do_c_expr_indent (); 705 } 706 } 707 708if (curwin -> w_p_rl ) { 709switch (s -> c ) { 710case K_LEFT : 711s -> c = K_RIGHT ;break ; 712case K_S_LEFT : 713s -> c = K_S_RIGHT ;break ; 714case K_C_LEFT : 715s -> c = K_C_RIGHT ;break ; 716case K_RIGHT : 717s -> c = K_LEFT ;break ; 718case K_S_RIGHT : 719s -> c = K_S_LEFT ;break ; 720case K_C_RIGHT : 721s -> c = K_C_LEFT ;break ; 722 } 723 } 724 725// If 'keymodel' contains "startsel", may start selection. If it 726// does, a CTRL-O and c will be stuffed, we need to get these 727// characters. 728if (ins_start_select (s -> c )) { 729return 1 ;// continue 730 } 731 732return insert_handle_key (s ); 733} 734 735static int insert_handle_key (InsertState * s ) 736{ 737// The big switch to handle a character in insert mode. 738switch (s -> c ) { 739case ESC :// End input mode 740if (echeck_abbr (ESC + ABBR_OFF )) { 741break ; 742 } 743FALLTHROUGH ; 744 745case Ctrl_C :// End input mode 746if (s -> c == Ctrl_C && bt_cmdwin (curbuf )) { 747got_int = false;// Don't interrupt autocmds etc. 748cmdwin_do_action ("cancel" );// cmdwin: CTRL-C closes cmdwin, pre-fills cmdline. 749return 0 ;// exit insert mode 750 } 751if (s -> c == Ctrl_C && bt_prompt (curbuf )) { 752if (invoke_prompt_interrupt ()) { 753if (!bt_prompt (curbuf )) { 754// buffer changed to a non-prompt buffer, get out of 755// Insert mode 756return 0 ; 757 } 758break ; 759 } 760 } 761 762return 0 ;// exit insert mode 763 764case Ctrl_Z : 765 gotonormalchar ;// insert CTRL-Z as normal char 766 767case Ctrl_O :// execute one command 768if (ctrl_x_mode_omni ()) { 769insert_do_complete (s ); 770break ; 771 } 772 773if (echeck_abbr (Ctrl_O + ABBR_OFF )) { 774break ; 775 } 776 777ins_ctrl_o (); 778 779// don't move the cursor left when 'virtualedit' has "onemore". 780if (get_ve_flags (curwin )& kOptVeFlagOnemore ) { 781ins_at_eol = false; 782s -> nomove = true; 783 } 784 785s -> count = 0 ; 786return 0 ;// exit insert mode 787 788case K_INS :// toggle insert/replace mode 789case K_KINS : 790ins_insert (s -> replaceState ); 791break ; 792 793case K_SELECT :// end of Select mode mapping - ignore 794break ; 795 796case K_HELP :// Help key works like <ESC> <Help> 797case K_F1 : 798case K_XF1 : 799stuffcharReadbuff (K_HELP ); 800return 0 ;// exit insert mode 801 802case ' ' : 803if (mod_mask != MOD_MASK_CTRL ) { 804 gotonormalchar ; 805 } 806FALLTHROUGH ; 807case K_ZERO :// Insert the previously inserted text. 808case NUL : 809case Ctrl_A : 810// For ^@ the trailing ESC will end the insert, unless there is an 811// error. 812if (stuff_inserted (NUL ,1 , (s -> c == Ctrl_A ))== FAIL 813&& s -> c != Ctrl_A ) { 814return 0 ;// exit insert mode 815 } 816s -> inserted_space = false; 817break ; 818 819case Ctrl_R :// insert the contents of a register 820if (ctrl_x_mode_register ()&& !ins_compl_active ()) { 821insert_do_complete (s ); 822break ; 823 } 824ins_reg (); 825auto_format (false, true); 826s -> inserted_space = false; 827break ; 828 829case Ctrl_G :// commands starting with CTRL-G 830ins_ctrl_g (); 831break ; 832 833case Ctrl_HAT :// switch input mode and/or langmap 834ins_ctrl_hat (); 835break ; 836 837case Ctrl__ :// switch between languages 838if (!p_ari ) { 839 gotonormalchar ; 840 } 841ins_ctrl_ (); 842break ; 843 844case Ctrl_D :// Make indent one shiftwidth smaller. 845if (ctrl_x_mode_path_defines ()) { 846insert_do_complete (s ); 847break ; 848 } 849FALLTHROUGH ; 850 851case Ctrl_T :// Make indent one shiftwidth greater. 852if (s -> c == Ctrl_T && ctrl_x_mode_thesaurus ()) { 853if (check_compl_option (false)) { 854insert_do_complete (s ); 855 } 856break ; 857 } 858ins_shift (s -> c ,s -> lastc ); 859auto_format (false, true); 860s -> inserted_space = false; 861break ; 862 863case K_DEL :// delete character under the cursor 864case K_KDEL : 865ins_del (); 866auto_format (false, true); 867break ; 868 869case K_BS :// delete character before the cursor 870case Ctrl_H : 871s -> did_backspace = ins_bs (s -> c ,BACKSPACE_CHAR ,& s -> inserted_space ); 872auto_format (false, true); 873if (s -> did_backspace ) { 874MAY_TRIGGER_AUTOCOMPLETE (s -> c ); 875 } 876break ; 877 878case Ctrl_W :// delete word before the cursor 879if (bt_prompt (curbuf )&& (mod_mask & MOD_MASK_SHIFT )== 0 ) { 880// In a prompt window CTRL-W is used for window commands. 881// Use Shift-CTRL-W to delete a word. 882stuffcharReadbuff (Ctrl_W ); 883restart_edit = 'A' ; 884s -> nomove = true; 885s -> count = 0 ; 886return 0 ; 887 } 888s -> did_backspace = ins_bs (s -> c ,BACKSPACE_WORD ,& s -> inserted_space ); 889auto_format (false, true); 890if (s -> did_backspace ) { 891MAY_TRIGGER_AUTOCOMPLETE (s -> c ); 892 } 893break ; 894 895case Ctrl_U :// delete all inserted text in current line 896// CTRL-X CTRL-U completes with 'completefunc'. 897if (ctrl_x_mode_function ()) { 898insert_do_complete (s ); 899 }else { 900s -> did_backspace = ins_bs (s -> c ,BACKSPACE_LINE ,& s -> inserted_space ); 901auto_format (false, true); 902s -> inserted_space = false; 903if (s -> did_backspace ) { 904MAY_TRIGGER_AUTOCOMPLETE (s -> c ); 905 } 906 } 907break ; 908 909case K_LEFTMOUSE :// mouse keys 910case K_LEFTMOUSE_NM : 911case K_LEFTDRAG : 912case K_LEFTRELEASE : 913case K_LEFTRELEASE_NM : 914case K_MOUSEMOVE : 915case K_MIDDLEMOUSE : 916case K_MIDDLEDRAG : 917case K_MIDDLERELEASE : 918case K_RIGHTMOUSE : 919case K_RIGHTDRAG : 920case K_RIGHTRELEASE : 921case K_X1MOUSE : 922case K_X1DRAG : 923case K_X1RELEASE : 924case K_X2MOUSE : 925case K_X2DRAG : 926case K_X2RELEASE : 927ins_mouse (s -> c ); 928break ; 929 930case K_MOUSEDOWN :// Default action for scroll wheel up: scroll up 931ins_mousescroll (MSCR_DOWN ); 932break ; 933 934case K_MOUSEUP :// Default action for scroll wheel down: scroll down 935ins_mousescroll (MSCR_UP ); 936break ; 937 938case K_MOUSELEFT :// Scroll wheel left 939ins_mousescroll (MSCR_LEFT ); 940break ; 941 942case K_MOUSERIGHT :// Scroll wheel right 943ins_mousescroll (MSCR_RIGHT ); 944break ; 945 946case K_IGNORE :// Something mapped to nothing 947break ; 948 949case K_PASTE_START : 950case K_EVENT :// some event 951case K_COMMAND :// <Cmd>command<CR> 952case K_LUA : { 953bufref_T save_curbuf ; 954const varnumber_T tick = buf_get_changedtick (curbuf ); 955set_bufref (& save_curbuf ,curbuf ); 956 957if (s -> c == K_PASTE_START ) { 958paste_repeat (1 ); 959 }else if (s -> c == K_EVENT ) { 960state_handle_k_event (); 961// If CTRL-G U was used apply it to the next typed key. 962if (Ins .dont_sync_undo == kTrue ) { 963Ins .dont_sync_undo = kNone ; 964 } 965 }else if (s -> c == K_COMMAND ) { 966do_cmdline (NULL ,getcmdkeycmd ,NULL ,0 ); 967 }else { 968map_execute_lua (false, false); 969 } 970 971// nvim_select_popupmenu_item() can be called from the handling of 972// K_EVENT, K_COMMAND, or K_LUA. 973// TODO(bfredl): Not entirely sure this indirection is necessary 974// but doing like this ensures using nvim_select_popupmenu_item is 975// equivalent to selecting the item with a typed key. 976if (pum_want .active ) { 977if (pum_visible ()) { 978// Set this to NULL so that ins_complete() will update the message. 979edit_submode_extra = NULL ; 980insert_do_complete (s ); 981if (pum_want .finish ) { 982// accept the item and stop completion 983ins_compl_prep (Ctrl_Y ); 984 } 985 } 986pum_want .active = false; 987 } 988 989if (curbuf -> b_u_synced 990|| (bufref_valid (& save_curbuf ) 991&& curbuf == save_curbuf .br_buf 992&& tick != buf_get_changedtick (curbuf ))) { 993// The K_EVENT, K_COMMAND, or K_LUA synced undo or changed this buffer. 994// Save the cursor line before the next typed edit. 995Ins .need_undo = true; 996 } 997break ; 998 } 999 1000case K_COMPLETE_DELAY :// 'autocompletedelay' expired 1001// If CTRL-G U was used apply it to the next typed key. 1002if (Ins .dont_sync_undo == kTrue ) { 1003Ins .dont_sync_undo = kNone ; 1004 } 1005ins_compl_clear_autocomplete_delay (); 1006if (!ins_compl_has_autocomplete ()|| char_avail ()|| curwin -> w_cursor .col == 0 ) { 1007break ; 1008 } 1009s -> c = char_before_cursor (); 1010if (!vim_isprintc (s -> c )) { 1011break ; 1012 } 1013// The completion may have been cleared while waiting, so re-enable 1014// autocomplete to match a zero delay. 1015ins_compl_enable_autocomplete (); 1016ins_compl_arm_autostart (); 1017insert_do_complete (s ); 1018break ; 1019 1020case K_HOME :// <Home> 1021case K_KHOME : 1022case K_S_HOME : 1023case K_C_HOME : 1024ins_home (s -> c ); 1025break ; 1026 1027case K_END :// <End> 1028case K_KEND : 1029case K_S_END : 1030case K_C_END : 1031ins_end (s -> c ); 1032break ; 1033 1034case K_LEFT :// <Left> 1035if (mod_mask & (MOD_MASK_SHIFT |MOD_MASK_CTRL )) { 1036ins_s_left (); 1037 }else { 1038ins_left (); 1039 } 1040break ; 1041 1042case K_S_LEFT :// <S-Left> 1043case K_C_LEFT : 1044ins_s_left (); 1045break ; 1046 1047case K_RIGHT :// <Right> 1048if (mod_mask & (MOD_MASK_SHIFT |MOD_MASK_CTRL )) { 1049ins_s_right (); 1050 }else { 1051ins_right (); 1052 } 1053break ; 1054 1055case K_S_RIGHT :// <S-Right> 1056case K_C_RIGHT : 1057ins_s_right (); 1058break ; 1059 1060case K_UP :// <Up> 1061if (pum_visible ()) { 1062insert_do_complete (s ); 1063 }else if (mod_mask & MOD_MASK_SHIFT ) { 1064ins_pageup (); 1065 }else { 1066ins_up (false); 1067 } 1068break ; 1069 1070case K_S_UP :// <S-Up> 1071case K_PAGEUP : 1072case K_KPAGEUP : 1073if (pum_visible ()) { 1074insert_do_complete (s ); 1075 }else { 1076ins_pageup (); 1077 } 1078break ; 1079 1080case K_DOWN :// <Down> 1081if (pum_visible ()) { 1082insert_do_complete (s ); 1083 }else if (mod_mask & MOD_MASK_SHIFT ) { 1084ins_pagedown (); 1085 }else { 1086ins_down (false); 1087 } 1088break ; 1089 1090case K_S_DOWN :// <S-Down> 1091case K_PAGEDOWN : 1092case K_KPAGEDOWN : 1093if (pum_visible ()) { 1094insert_do_complete (s ); 1095 }else { 1096ins_pagedown (); 1097 } 1098break ; 1099 1100case K_S_TAB :// When not mapped, use like a normal TAB 1101s -> c = TAB ; 1102FALLTHROUGH ; 1103 1104case TAB :// TAB or Complete patterns along path 1105if (ctrl_x_mode_path_patterns ()) { 1106insert_do_complete (s ); 1107break ; 1108 } 1109s -> inserted_space = false; 1110if (ins_tab ()) { 1111 gotonormalchar ;// insert TAB as a normal char 1112 } 1113auto_format (false, true); 1114break ; 1115 1116case K_KENTER :// <Enter> 1117s -> c = CAR ; 1118FALLTHROUGH ; 1119case CAR : 1120case NL : 1121// In a quickfix window a <CR> jumps to the error under the 1122// cursor. 1123if (bt_quickfix (curbuf )&& s -> c == CAR ) { 1124if (curwin -> w_llist_ref == NULL ) {// quickfix window 1125do_cmdline_cmd (".cc" ); 1126 }else {// location list window 1127do_cmdline_cmd (".ll" ); 1128 } 1129break ; 1130 } 1131if (s -> c == CAR && bt_cmdwin (curbuf )) { 1132cmdwin_do_action ("confirm" );// cmdwin: <CR> executes the command under the cursor. 1133return 0 ;// exit insert mode 1134 } 1135if ((mod_mask & MOD_MASK_SHIFT )== 0 && bt_prompt (curbuf )) { 1136prompt_invoke_callback (); 1137if (!bt_prompt (curbuf )) { 1138// buffer changed to a non-prompt buffer, get out of 1139// Insert mode 1140return 0 ; 1141 } 1142break ; 1143 } 1144if (!ins_eol (s -> c )) { 1145return 0 ;// out of memory 1146 } 1147auto_format (false, false); 1148s -> inserted_space = false; 1149break ; 1150 1151case Ctrl_K :// digraph or keyword completion 1152if (ctrl_x_mode_dictionary ()) { 1153if (check_compl_option (true)) { 1154insert_do_complete (s ); 1155 } 1156break ; 1157 } 1158 1159s -> c = ins_digraph (); 1160if (s -> c == NUL ) { 1161break ; 1162 } 1163 gotonormalchar ; 1164 1165case Ctrl_X :// Enter CTRL-X mode 1166ins_ctrl_x (); 1167break ; 1168 1169case Ctrl_RSB :// Tag name completion after ^X 1170if (!ctrl_x_mode_tags ()) { 1171 gotonormalchar ; 1172 }else { 1173insert_do_complete (s ); 1174 } 1175break ; 1176 1177case Ctrl_F :// File name completion after ^X 1178if (!ctrl_x_mode_files ()) { 1179 gotonormalchar ; 1180 }else { 1181insert_do_complete (s ); 1182 } 1183break ; 1184 1185case 's' :// Spelling completion after ^X 1186case Ctrl_S : 1187if (!ctrl_x_mode_spell ()) { 1188 gotonormalchar ; 1189 }else { 1190insert_do_complete (s ); 1191 } 1192break ; 1193 1194case Ctrl_L :// Whole line completion after ^X 1195if (!ctrl_x_mode_whole_line ()) { 1196 gotonormalchar ; 1197 } 1198FALLTHROUGH ; 1199 1200case Ctrl_P :// Do previous/next pattern completion 1201case Ctrl_N : 1202// if 'complete' is empty then plain ^P is no longer special, 1203// but it is under other ^X modes 1204if (* curbuf -> b_p_cpt == NUL 1205&& (ctrl_x_mode_normal ()|| ctrl_x_mode_whole_line ()) 1206&& !compl_status_local ()) { 1207 gotonormalchar ; 1208 } 1209 1210insert_do_complete (s ); 1211break ; 1212 1213case Ctrl_Y :// copy from previous line or scroll down 1214case Ctrl_E :// copy from next line or scroll up 1215s -> c = ins_ctrl_ey (s -> c ); 1216break ; 1217 1218default : 1219 1220normalchar : 1221// Insert a normal character. 1222 1223if (!p_paste ) { 1224// Trigger InsertCharPre. 1225char * str = do_insert_char_pre (s -> c ); 1226 1227if (str != NULL ) { 1228if (* str != NUL && stop_arrow ()!= FAIL ) { 1229// Insert the new value of v:char literally. 1230for (char * p = str ;* p != NUL ;MB_PTR_ADV (p )) { 1231s -> c = utf_ptr2char (p ); 1232if (s -> c == CAR || s -> c == K_KENTER || s -> c == NL ) { 1233ins_eol (s -> c ); 1234 }else { 1235ins_char (s -> c ); 1236 } 1237 } 1238redo_append_lit (str ,-1 ); 1239 } 1240xfree (str ); 1241s -> c = NUL ; 1242 } 1243 1244// If the new value is already inserted or an empty string 1245// then don't insert any character. 1246if (s -> c == NUL ) { 1247break ; 1248 } 1249 } 1250// Try to perform smart-indenting. 1251ins_try_si (s -> c ); 1252 1253if (s -> c == ' ' ) { 1254s -> inserted_space = true; 1255if (inindent (0 )) { 1256Ins .can_cindent = false; 1257 } 1258if (Ins .start_blank_vcol == MAXCOL 1259&& curwin -> w_cursor .lnum == Ins .start .lnum ) { 1260Ins .start_blank_vcol = get_nolist_virtcol (); 1261 } 1262 } 1263 1264// Insert a normal character and check for abbreviations on a 1265// special character. Let CTRL-] expand abbreviations without 1266// inserting it. 1267if (vim_iswordc (s -> c ) 1268// Add ABBR_OFF for characters above 0x100, this is 1269// what check_abbr() expects. 1270|| (!echeck_abbr ((s -> c >=0x100 ) ? (s -> c + ABBR_OFF ) :s -> c ) 1271&& s -> c != Ctrl_RSB )) { 1272insert_special (s -> c , false, false); 1273Ins .revins_legal ++ ; 1274Ins .revins_chars ++ ; 1275 } 1276 1277auto_format (false, true); 1278 1279// When inserting a character the cursor line must never be in a 1280// closed fold. 1281foldOpenCursor (); 1282// Trigger autocompletion 1283if (ins_compl_has_autocomplete ()&& !char_avail ()&& vim_isprintc (s -> c )) { 1284TRIGGER_AUTOCOMPLETE (); 1285 } 1286 1287break ; 1288 }// end of switch (s->c) 1289 1290insert_handle_key_post (s ); 1291return 1 ;// continue 1292} 1293 1294static void insert_do_complete (InsertState * s ) 1295{ 1296ins_compl_clear_autocomplete_delay (); 1297compl_busy = true; 1298disable_fold_update ++ ;// don't redraw folds here 1299if (ins_complete (s -> c , true)== FAIL ) { 1300compl_status_clear (); 1301 } 1302disable_fold_update -- ; 1303compl_busy = false; 1304Ins .can_si = may_do_si ();// allow smartindenting 1305} 1306 1307static void insert_do_cindent (InsertState * s ) 1308{ 1309// Indent now if a key was typed that is in 'cinkeys'. 1310if (in_cinkeys (s -> c ,' ' ,s -> line_is_white )) { 1311if (stop_arrow ()== OK ) { 1312// re-indent the current line 1313do_c_expr_indent (); 1314 } 1315 } 1316} 1317 1318static void insert_handle_key_post (InsertState * s ) 1319{ 1320// If typed something may trigger CursorHoldI again; K_COMPLETE_DELAY is 1321// injected, not typed. 1322if (s -> c != K_EVENT && s -> c != K_COMPLETE_DELAY 1323// but not in CTRL-X mode, a script can't restore the state 1324&& ctrl_x_mode_normal ()) { 1325did_cursorhold = false; 1326 } 1327 1328// Check if we need to cancel completion mode because the window 1329// or tab page was changed 1330if (ins_compl_active ()&& !ins_compl_win_active (curwin )) { 1331ins_compl_cancel (); 1332 } 1333 1334// If the cursor was moved we didn't just insert a space 1335if (Ins .moved != kInsNone ) { 1336s -> inserted_space = false; 1337 } 1338 1339if (Ins .can_cindent && cindent_on ()&& ctrl_x_mode_normal ()) { 1340insert_do_cindent (s ); 1341 } 1342} 1343 1344/// edit(): Start inserting text. 1345/// 1346/// May nest: ":normal i…" and multicursor insert-cascade enters it while an outer edit() is 1347/// suspended. But i_CTRL-O does not nest: edit() returns, and the caller runs the Normal-mode 1348/// command. 1349/// 1350/// @param cmdchar Command that started the insert: 1351/// - 'i' 1352/// - 'a' 1353/// - 'R' 1354/// - 'r': "r<CR>" command: insert one <CR>. Note: count can be > 1, for redo, but still only one 1355/// <CR> is inserted. <Esc> is not used for redo. 1356/// - 'g': "gI" command. 1357/// - 'V': "gR" command: Virtual Replace mode. 1358/// - 'v': "gr" command: single-character Virtual Replace mode. 1359/// @param startln If true, insert at start of line. 1360/// @param count Repeat count for the command. 1361/// 1362/// @return true if a CTRL-O command caused the return (insert mode pending). 1363bool edit (int cmdchar ,bool startln ,int count ) 1364{ 1365if (curbuf -> terminal ) { 1366if (ex_normal_busy ) { 1367// Do not enter terminal mode from ex_normal(), which would cause havoc 1368// (such as terminal-mode recursiveness). Instead set a flag to force-set 1369// the value of `restart_edit` before `ex_normal` returns. 1370restart_edit = 'i' ; 1371force_restart_edit = true; 1372return false; 1373 } 1374return terminal_enter (); 1375 } 1376 1377// Don't allow inserting in the sandbox. 1378if (sandbox != 0 ) { 1379emsg (_ (e_sandbox )); 1380return false; 1381 } 1382 1383// Disallow edit() (insert-mode) when: 1384// - ins-completion is active 1385// - textlock (the caller of getcmdline() may get confused) 1386// - <expr> mapping eval 1387if (textlock != 0 || ins_compl_active ()|| compl_busy || pum_visible () 1388|| expr_map_locked ()) { 1389emsg (_ (e_textlock )); 1390return false; 1391 } 1392 1393InsertState s [1 ]; 1394memset (s ,0 ,sizeof (InsertState )); 1395s -> state .execute = insert_execute ; 1396s -> state .check = insert_check ; 1397s -> cmdchar = cmdchar ; 1398s -> startln = startln ; 1399s -> count = count ; 1400insert_enter (s ); 1401return s -> c == Ctrl_O ; 1402} 1403 1404/// Redraw for Insert mode. 1405/// This is postponed until getting the next character to make '$' in the 'cpo' 1406/// option work correctly. 1407/// Only redraw when there are no characters available. This speeds up 1408/// inserting sequences of characters (e.g., for CTRL-R). 1409/// 1410/// @param ready not busy with something 1411void ins_redraw (bool ready ) 1412{ 1413if (char_avail ()) { 1414return ; 1415 } 1416 1417// Trigger CursorMoved if the cursor moved. Not when the popup menu is 1418// visible, the command might delete it. 1419if (ready && has_event (EVENT_CURSORMOVEDI ) 1420&& (last_cursormoved_win != curwin 1421|| !equalpos (last_cursormoved ,curwin -> w_cursor )) 1422&& !pum_visible ()) { 1423// Need to update the screen first, to make sure syntax 1424// highlighting is correct after making a change (e.g., inserting 1425// a "(". The autocommand may also require a redraw, so it's done 1426// again below, unfortunately. 1427if (syntax_present (curwin )&& must_redraw ) { 1428update_screen (); 1429 } 1430// Make sure curswant is correct, an autocommand may call 1431// getcurpos() 1432update_curswant (); 1433ins_apply_autocmds (EVENT_CURSORMOVEDI ); 1434last_cursormoved_win = curwin ; 1435last_cursormoved = curwin -> w_cursor ; 1436 } 1437 1438// Trigger TextChangedI if changedtick_i differs. 1439if (ready && has_event (EVENT_TEXTCHANGEDI ) 1440&& curbuf -> b_last_changedtick_i != buf_get_changedtick (curbuf ) 1441&& !pum_visible ()) { 1442CtxSwitch aco = {0 }; 1443varnumber_T tick = buf_get_changedtick (curbuf ); 1444 1445// save and restore curwin and curbuf, in case the autocmd changes them 1446ctx_switch (& aco ,NULL ,NULL ,curbuf ,0 ); 1447apply_autocmds (EVENT_TEXTCHANGEDI ,NULL ,NULL , false,curbuf ); 1448ctx_restore (& aco ); 1449curbuf -> b_last_changedtick_i = buf_get_changedtick (curbuf ); 1450if (tick != buf_get_changedtick (curbuf )) {// see ins_apply_autocmds() 1451u_save (curwin -> w_cursor .lnum , 1452 (linenr_T )(curwin -> w_cursor .lnum + 1 )); 1453 } 1454 } 1455 1456// Trigger TextChangedP if changedtick_pum differs. When the popupmenu 1457// closes TextChangedI will need to trigger for backwards compatibility, 1458// thus use different b_last_changedtick* variables. 1459if (ready && has_event (EVENT_TEXTCHANGEDP ) 1460&& curbuf -> b_last_changedtick_pum != buf_get_changedtick (curbuf ) 1461&& pum_visible ()) { 1462CtxSwitch aco = {0 }; 1463varnumber_T tick = buf_get_changedtick (curbuf ); 1464 1465// save and restore curwin and curbuf, in case the autocmd changes them 1466ctx_switch (& aco ,NULL ,NULL ,curbuf ,0 ); 1467apply_autocmds (EVENT_TEXTCHANGEDP ,NULL ,NULL , false,curbuf ); 1468ctx_restore (& aco ); 1469curbuf -> b_last_changedtick_pum = buf_get_changedtick (curbuf ); 1470if (tick != buf_get_changedtick (curbuf )) {// see ins_apply_autocmds() 1471u_save (curwin -> w_cursor .lnum , 1472 (linenr_T )(curwin -> w_cursor .lnum + 1 )); 1473 } 1474 } 1475 1476if (ready ) { 1477may_trigger_win_scrolled_resized (); 1478 } 1479 1480// Trigger SafeState if nothing is pending. 1481may_trigger_safestate (ready && !ins_compl_active ()&& !pum_visible ()); 1482 1483pum_check_clear (); 1484show_cursor_info_later (false); 1485if (must_redraw ) { 1486update_screen (); 1487 }else { 1488redraw_statuslines (); 1489if (clear_cmdline || redraw_cmdline || redraw_mode ) { 1490showmode ();// clear cmdline and show mode 1491 } 1492 } 1493setcursor (); 1494emsg_on_display = false;// may remove error message now 1495} 1496 1497// Handle a CTRL-V or CTRL-Q typed in Insert mode. 1498static void ins_ctrl_v (void ) 1499{ 1500bool did_putchar = false; 1501 1502// may need to redraw when no more chars available now 1503ins_redraw (false); 1504 1505if (redrawing ()&& !char_avail ()) { 1506edit_putchar ('^' , true); 1507did_putchar = true; 1508 } 1509redo_append_str (S_LEN (CTRL_V_STR )); 1510 1511add_to_showcmd_c (Ctrl_V ); 1512 1513// Do not include modifiers into the key for CTRL-SHIFT-V. 1514int c = get_literal (mod_mask & MOD_MASK_SHIFT ); 1515if (did_putchar ) { 1516// when the line fits in 'columns' the '^' is at the start of the next 1517// line and will not removed by the redraw 1518edit_unputchar (); 1519 } 1520clear_showcmd (); 1521insert_special (c , true, true); 1522Ins .revins_chars ++ ; 1523Ins .revins_legal ++ ; 1524} 1525 1526// Put a character directly onto the screen. It's not stored in a buffer. 1527// Used while handling CTRL-K, CTRL-V, etc. in Insert mode. 1528static int pc_status ; 1529#define PC_STATUS_UNSET 0 // nothing was put on screen 1530#define PC_STATUS_RIGHT 1 // right half of double-wide char 1531#define PC_STATUS_LEFT 2 // left half of double-wide char 1532#define PC_STATUS_SET 3 // pc_schar was filled 1533static schar_T pc_schar ;// saved char 1534static int pc_attr ; 1535static int pc_row ; 1536static int pc_col ; 1537 1538void edit_putchar (int c ,bool highlight ) 1539{ 1540if (curwin -> w_grid_alloc .chars == NULL && default_grid .chars == NULL ) { 1541return ; 1542 } 1543 1544int attr ; 1545update_topline (curwin );// just in case w_topline isn't valid 1546validate_cursor (curwin ); 1547if (highlight ) { 1548attr = HL_ATTR (HLF_8 ); 1549 }else { 1550attr = 0 ; 1551 } 1552pc_row = curwin -> w_wrow ; 1553pc_status = PC_STATUS_UNSET ; 1554grid_line_start (& curwin -> w_grid ,pc_row ); 1555if (curwin -> w_p_rl ) { 1556pc_col = curwin -> w_view_width - 1 - curwin -> w_wcol ; 1557 1558if (grid_line_getchar (pc_col ,NULL )== NUL ) { 1559grid_line_put_schar (pc_col - 1 ,schar_from_ascii (' ' ),attr ); 1560curwin -> w_wcol -- ; 1561pc_status = PC_STATUS_RIGHT ; 1562 } 1563 }else { 1564pc_col = curwin -> w_wcol ; 1565 1566if (grid_line_getchar (pc_col + 1 ,NULL )== NUL ) { 1567// pc_col is the left half of a double-width char 1568pc_status = PC_STATUS_LEFT ; 1569 } 1570 } 1571 1572// save the character to be able to put it back 1573if (pc_status == PC_STATUS_UNSET ) { 1574pc_schar = grid_line_getchar (pc_col ,& pc_attr ); 1575pc_status = PC_STATUS_SET ; 1576 } 1577 1578char buf [MB_MAXCHAR + 1 ]; 1579grid_line_puts (pc_col ,buf ,utf_char2bytes (c ,buf ),attr ); 1580grid_line_flush (); 1581} 1582 1583/// @return the effective prompt for the specified buffer. 1584char * buf_prompt_text (const buf_T * const buf ) 1585FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 1586{ 1587if (buf -> b_prompt_text == NULL ) { 1588return "% " ; 1589 } 1590return buf -> b_prompt_text ; 1591} 1592 1593/// @return the effective prompt for the current buffer. 1594char * prompt_text (void ) 1595FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 1596{ 1597return buf_prompt_text (curbuf ); 1598} 1599 1600// Prepare for prompt mode (buftype=prompt): Make sure the last line has the prompt text. 1601// Move the cursor to this line. 1602static void init_prompt (int cmdchar_todo ) 1603{ 1604char * prompt = prompt_text (); 1605int prompt_len = (int )strlen (prompt ); 1606 1607// In case the mark is set to a nonexistent line. 1608if (curbuf -> b_prompt_start .mark .lnum < 1 1609|| curbuf -> b_prompt_start .mark .lnum > curbuf -> b_ml .ml_line_count ) { 1610curbuf -> b_prompt_start .mark .lnum = MAX (1 ,MIN (curbuf -> b_prompt_start .mark .lnum , 1611curbuf -> b_ml .ml_line_count )); 1612curbuf -> b_prompt_append_new_line = true; 1613 } 1614 1615curwin -> w_cursor .lnum = MAX (curwin -> w_cursor .lnum ,curbuf -> b_prompt_start .mark .lnum ); 1616char * text = ml_get (curbuf -> b_prompt_start .mark .lnum ); 1617colnr_T text_len = ml_get_len (curbuf -> b_prompt_start .mark .lnum ); 1618 1619if ((curbuf -> b_prompt_start .mark .lnum == curwin -> w_cursor .lnum 1620&& (curbuf -> b_prompt_start .mark .col < prompt_len 1621|| curbuf -> b_prompt_start .mark .col > text_len 1622|| !strnequal (text + curbuf -> b_prompt_start .mark .col - prompt_len ,prompt , 1623 (size_t )prompt_len )))) { 1624// prompt is missing, insert it or append a line with it 1625if (* text == NUL ) { 1626ml_replace (curbuf -> b_prompt_start .mark .lnum ,prompt , true); 1627inserted_bytes (curbuf -> b_prompt_start .mark .lnum ,0 ,0 ,prompt_len ); 1628 }else { 1629const linenr_T lnum = curbuf -> b_ml .ml_line_count ; 1630ml_append (lnum ,prompt ,0 , false); 1631appended_lines_mark (lnum ,1 ); 1632curbuf -> b_prompt_start .mark .lnum = curbuf -> b_ml .ml_line_count ; 1633curbuf -> b_prompt_append_new_line = true; 1634// Like submitting, undo history was relevant to the old prompt. 1635u_clearallandblockfree (curbuf ); 1636 } 1637curbuf -> b_prompt_start .mark .col = prompt_len ; 1638curwin -> w_cursor .lnum = curbuf -> b_ml .ml_line_count ; 1639coladvance (curwin ,MAXCOL ); 1640 } 1641 1642// Insert always starts after the prompt, allow editing text after it. 1643if (Ins .start_orig .lnum != curbuf -> b_prompt_start .mark .lnum 1644|| Ins .start_orig .col != curbuf -> b_prompt_start .mark .col ) { 1645set_insstart (curbuf -> b_prompt_start .mark .lnum ,curbuf -> b_prompt_start .mark .col ); 1646 } 1647 1648if (cmdchar_todo == 'A' ) { 1649coladvance (curwin ,MAXCOL ); 1650 } 1651if (curbuf -> b_prompt_start .mark .lnum == curwin -> w_cursor .lnum ) { 1652curwin -> w_cursor .col = MAX (curwin -> w_cursor .col ,curbuf -> b_prompt_start .mark .col ); 1653 } 1654// Make sure the cursor is in a valid position. 1655check_cursor (curwin ); 1656} 1657 1658/// @return true if the cursor is in the editable position of the prompt line. 1659bool prompt_curpos_editable (void ) 1660FUNC_ATTR_PURE 1661{ 1662return curwin -> w_cursor .lnum > curbuf -> b_prompt_start .mark .lnum 1663|| (curwin -> w_cursor .lnum == curbuf -> b_prompt_start .mark .lnum 1664&& curwin -> w_cursor .col >=curbuf -> b_prompt_start .mark .col ); 1665} 1666 1667/// Set the insert start position for when using a prompt buffer. 1668/// 1669/// @param[in] lnum 1670/// @param[in] col 1671static void set_insstart (linenr_T lnum ,colnr_T col ) 1672{ 1673Ins .start .lnum = lnum ; 1674Ins .start .col = col ; 1675Ins .start_orig = Ins .start ; 1676Ins .start_textlen = Ins .start .col ; 1677Ins .start_blank_vcol = MAXCOL ; 1678Ins .moved = kInsNone ; 1679} 1680 1681// Undo the previous edit_putchar(). 1682void edit_unputchar (void ) 1683{ 1684if (pc_status != PC_STATUS_UNSET ) { 1685if (pc_status == PC_STATUS_RIGHT ) { 1686curwin -> w_wcol ++ ; 1687 } 1688if (pc_status == PC_STATUS_RIGHT || pc_status == PC_STATUS_LEFT ) { 1689redrawWinline (curwin ,curwin -> w_cursor .lnum ); 1690 }else { 1691// TODO(bfredl): this could be smarter and also handle the dubyawidth case 1692grid_line_start (& curwin -> w_grid ,pc_row ); 1693grid_line_put_schar (pc_col ,pc_schar ,pc_attr ); 1694grid_line_flush (); 1695 } 1696 } 1697} 1698 1699/// Called when "$" is in 'cpoptions': display a '$' at the end of the changed 1700/// text. Only works when cursor is in the line that changes. 1701void display_dollar (colnr_T col_arg ) 1702{ 1703colnr_T col = MAX (col_arg ,0 ); 1704 1705if (!redrawing ()) { 1706return ; 1707 } 1708 1709colnr_T save_col = curwin -> w_cursor .col ; 1710curwin -> w_cursor .col = col ; 1711 1712// If on the last byte of a multi-byte move to the first byte. 1713char * p = get_cursor_line_ptr (); 1714curwin -> w_cursor .col -= utf_head_off (p ,p + col ); 1715curs_columns (curwin , false);// Recompute w_wrow and w_wcol 1716if (curwin -> w_wcol < curwin -> w_view_width ) { 1717edit_putchar ('$' , false); 1718dollar_vcol = curwin -> w_virtcol ; 1719 } 1720curwin -> w_cursor .col = save_col ; 1721} 1722 1723// Call this function before moving the cursor from the normal insert position 1724// in insert mode. 1725void undisplay_dollar (void ) 1726{ 1727if (dollar_vcol < 0 ) { 1728return ; 1729 } 1730 1731dollar_vcol = -1 ; 1732redrawWinline (curwin ,curwin -> w_cursor .lnum ); 1733} 1734 1735/// Truncate the space at the end of a line. This is to be used only in an 1736/// insert mode. It handles fixing the replace stack for MODE_REPLACE and 1737/// MODE_VREPLACE modes. 1738void truncate_spaces (char * line ,size_t len ) 1739{ 1740int i ; 1741 1742// find start of trailing white space 1743for (i = (int )len - 1 ;i >=0 && ascii_iswhite (line [i ]);i -- ) { 1744if (State & REPLACE_FLAG ) { 1745replace_join (0 );// remove a NUL from the replace stack 1746 } 1747 } 1748line [i + 1 ]= NUL ; 1749} 1750 1751/// Backspace the cursor until the given column. Handles MODE_REPLACE and 1752/// MODE_VREPLACE modes correctly. May also be used when not in insert mode at 1753/// all. Will attempt not to go before "col" even when there is a composing 1754/// character. 1755void backspace_until_column (int col ) 1756{ 1757while ((int )curwin -> w_cursor .col > col ) { 1758curwin -> w_cursor .col -- ; 1759if (State & REPLACE_FLAG ) { 1760replace_do_bs (col ); 1761 }else if (!del_char_after_col (col )) { 1762break ; 1763 } 1764 } 1765} 1766 1767/// Like del_char(), but make sure not to go before column "limit_col". 1768/// Only matters when there are composing characters. 1769/// 1770/// @param limit_col only delete the character if it is after this column 1771// 1772/// @return true when something was deleted. 1773static bool del_char_after_col (int limit_col ) 1774{ 1775if (limit_col >=0 ) { 1776colnr_T ecol = curwin -> w_cursor .col + 1 ; 1777 1778// Make sure the cursor is at the start of a character, but 1779// skip forward again when going too far back because of a 1780// composing character. 1781mb_adjust_cursor (); 1782while (curwin -> w_cursor .col < (colnr_T )limit_col ) { 1783int l = utf_ptr2len (get_cursor_pos_ptr ()); 1784 1785if (l == 0 ) {// end of line 1786break ; 1787 } 1788curwin -> w_cursor .col += l ; 1789 } 1790if (* get_cursor_pos_ptr ()== NUL || curwin -> w_cursor .col == ecol ) { 1791return false; 1792 } 1793del_bytes (ecol - curwin -> w_cursor .col , false, true); 1794 }else { 1795del_char (false); 1796 } 1797return true; 1798} 1799 1800/// Next character is interpreted literally. 1801/// A one, two or three digit decimal number is interpreted as its byte value. 1802/// If one or two digits are entered, the next character is given to vungetc(). 1803/// For Unicode a character > 255 may be returned. 1804/// 1805/// @param no_simplify do not include modifiers into the key 1806int get_literal (bool no_simplify ) 1807{ 1808int nc ; 1809bool hex = false; 1810bool octal = false; 1811int unicode = 0 ; 1812 1813if (got_int ) { 1814return Ctrl_C ; 1815 } 1816 1817no_mapping ++ ;// don't map the next key hits 1818int cc = 0 ; 1819int i = 0 ; 1820while (true) { 1821nc = plain_vgetc (); 1822if (!no_simplify ) { 1823nc = merge_modifiers (nc ,& mod_mask ); 1824 } 1825if ((mod_mask & ~MOD_MASK_SHIFT )!= 0 ) { 1826// A character with non-Shift modifiers should not be a valid 1827// character for i_CTRL-V_digit. 1828break ; 1829 } 1830if ((State & MODE_CMDLINE )== 0 && MB_BYTE2LEN_CHECK (nc )== 1 ) { 1831add_to_showcmd (nc ); 1832 } 1833if (nc == 'x' || nc == 'X' ) { 1834hex = true; 1835 }else if (nc == 'o' || nc == 'O' ) { 1836octal = true; 1837 }else if (nc == 'u' || nc == 'U' ) { 1838unicode = nc ; 1839 }else { 1840if (hex 1841|| unicode != 0 ) { 1842if (!ascii_isxdigit (nc )) { 1843break ; 1844 } 1845cc = cc * 16 + hex2nr (nc ); 1846 }else if (octal ) { 1847if (nc < '0' || nc > '7' ) { 1848break ; 1849 } 1850cc = cc * 8 + nc - '0' ; 1851 }else { 1852if (!ascii_isdigit (nc )) { 1853break ; 1854 } 1855cc = cc * 10 + nc - '0' ; 1856 } 1857 1858i ++ ; 1859 } 1860 1861if (cc > 255 1862&& unicode == 0 ) { 1863cc = 255 ;// limit range to 0-255 1864 } 1865nc = 0 ; 1866 1867if (hex ) {// hex: up to two chars 1868if (i >=2 ) { 1869break ; 1870 } 1871 }else if (unicode ) {// Unicode: up to four or eight chars 1872if ((unicode == 'u' && i >=4 )|| (unicode == 'U' && i >=8 )) { 1873break ; 1874 } 1875 }else if (i >=3 ) {// decimal or octal: up to three chars 1876break ; 1877 } 1878 } 1879if (i == 0 ) {// no number entered 1880if (nc == K_ZERO ) {// NUL is stored as NL 1881cc = '\n' ; 1882nc = 0 ; 1883 }else { 1884cc = nc ; 1885nc = 0 ; 1886 } 1887 } 1888 1889if (cc == 0 ) {// NUL is stored as NL 1890cc = '\n' ; 1891 } 1892 1893no_mapping -- ; 1894if (nc ) { 1895vungetc (nc ); 1896// A character typed with i_CTRL-V_digit cannot have modifiers. 1897mod_mask = 0 ; 1898 } 1899got_int = false;// CTRL-C typed after CTRL-V is not an interrupt 1900return cc ; 1901} 1902 1903/// Insert character, taking care of special keys and mod_mask 1904/// 1905/// @param ctrlv `c` was typed after CTRL-V 1906static void insert_special (int c ,int allow_modmask ,int ctrlv ) 1907{ 1908// Special function key, translate into "<Key>". Up to the last '>' is 1909// inserted with ins_str(), so as not to replace characters in replace 1910// mode. 1911// Only use mod_mask for special keys, to avoid things like <S-Space>, 1912// unless 'allow_modmask' is true. 1913if (mod_mask & MOD_MASK_CMD ) {// Command-key never produces a normal key. 1914allow_modmask = true; 1915 } 1916if (IS_SPECIAL (c )|| (mod_mask && allow_modmask )) { 1917char * p = get_special_key_name (c ,mod_mask ); 1918int len = (int )strlen (p ); 1919c = (uint8_t )p [len - 1 ]; 1920if (len > 2 ) { 1921if (stop_arrow ()== FAIL ) { 1922return ; 1923 } 1924p [len - 1 ]= NUL ; 1925ins_str (p , (size_t )(len - 1 )); 1926redo_append_lit (p ,-1 ); 1927ctrlv = false; 1928 } 1929 } 1930if (stop_arrow ()== OK ) { 1931insertchar (c ,ctrlv ?INSCHAR_CTRLV :0 ,-1 ); 1932 } 1933} 1934 1935// Special characters in this context are those that need processing other 1936// than the simple insertion that can be performed here. This includes ESC 1937// which terminates the insert, and CR/NL which need special processing to 1938// open up a new line. This routine tries to optimize insertions performed by 1939// the "redo", "undo" or "put" commands, so it needs to know when it should 1940// stop and defer processing to the "normal" mechanism. 1941// '0' and '^' are special, because they can be followed by CTRL-D. 1942#define ISSPECIAL (c ) ((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^') 1943 1944/// "flags": INSCHAR_FORMAT - force formatting 1945/// INSCHAR_CTRLV - char typed just after CTRL-V 1946/// INSCHAR_NO_FEX - don't use 'formatexpr' 1947/// 1948/// NOTE: passes the flags value straight through to internal_format() which, 1949/// beside INSCHAR_FORMAT (above), is also looking for these: 1950/// INSCHAR_DO_COM - format comments 1951/// INSCHAR_COM_LIST - format comments with num list or 2nd line indent 1952/// 1953/// @param c character to insert or NUL 1954/// @param flags INSCHAR_FORMAT, etc. 1955/// @param second_indent indent for second line if >= 0 1956void insertchar (int c ,int flags ,int second_indent ) 1957{ 1958char * p ; 1959int force_format = flags & INSCHAR_FORMAT ; 1960 1961const int textwidth = comp_textwidth (force_format ); 1962const bool fo_ins_blank = has_format_option (kFoInsBlank ); 1963 1964// Try to break the line in two or more pieces when: 1965// - Always do this if we have been called to do formatting only. 1966// - Always do this when 'formatoptions' has the 'a' flag and the line 1967// ends in white space. 1968// - Otherwise: 1969// - Don't do this if inserting a blank 1970// - Don't do this if an existing character is being replaced, unless 1971// we're in MODE_VREPLACE state. 1972// - Do this if the cursor is not on the line where insert started 1973// or - 'formatoptions' doesn't have 'l' or the line was not too long 1974// before the insert. 1975// - 'formatoptions' doesn't have 'b' or a blank was inserted at or 1976// before 'textwidth' 1977if (textwidth > 0 1978&& (force_format 1979|| (!ascii_iswhite (c ) 1980&& !((State & REPLACE_FLAG ) 1981&& !(State & VREPLACE_FLAG ) 1982&& * get_cursor_pos_ptr ()!= NUL ) 1983&& (curwin -> w_cursor .lnum != Ins .start .lnum 1984|| ((!has_format_option (kFoInsLong ) 1985|| Ins .start_textlen <= (colnr_T )textwidth ) 1986&& (!fo_ins_blank 1987|| Ins .start_blank_vcol <= (colnr_T )textwidth )))))) { 1988// Format with 'formatexpr' when it's set. Use internal formatting 1989// when 'formatexpr' isn't set or it returns non-zero. 1990bool do_internal = true; 1991colnr_T virtcol = get_nolist_virtcol () 1992+ char2cells (c != NUL ?c :gchar_cursor ()); 1993 1994if (curbuf -> b_p_fex .type != kCallbackNone && (flags & INSCHAR_NO_FEX )== 0 1995&& (force_format || virtcol > (colnr_T )textwidth )) { 1996do_internal = (fex_format (curwin -> w_cursor .lnum ,1 ,c )!= 0 ); 1997// It may be required to save for undo again, e.g. when setline() 1998// was called. 1999Ins .need_undo = true; 2000 } 2001if (do_internal ) { 2002internal_format (textwidth ,second_indent ,flags ,c == NUL ,c ); 2003 } 2004 } 2005 2006if (c == NUL ) {// only formatting was wanted 2007return ; 2008 } 2009 2010// Check whether this character should end a comment. 2011if (Ins .did_ai && c == Ins .end_comment_pending ) { 2012char lead_end [COM_MAX_LEN ];// end-comment string 2013 2014// Need to remove existing (middle) comment leader and insert end 2015// comment leader. First, check what comment leader we can find. 2016char * line = get_cursor_line_ptr (); 2017int i = get_leader_len (line ,& p , false, true); 2018if (i > 0 && vim_strchr (p ,COM_MIDDLE )!= NULL ) {// Just checking 2019// Skip middle-comment string 2020while (* p && p [-1 ]!= ':' ) {// find end of middle flags 2021p ++ ; 2022 } 2023int middle_len = (int )copy_option_part (& p ,lead_end ,COM_MAX_LEN ,"," ); 2024// Don't count trailing white space for middle_len 2025while (middle_len > 0 && ascii_iswhite (lead_end [middle_len - 1 ])) { 2026middle_len -- ; 2027 } 2028 2029// Find the end-comment string 2030while (* p && p [-1 ]!= ':' ) {// find end of end flags 2031p ++ ; 2032 } 2033int end_len = (int )copy_option_part (& p ,lead_end ,COM_MAX_LEN ,"," ); 2034 2035// Skip white space before the cursor 2036i = curwin -> w_cursor .col ; 2037while (-- i >=0 && ascii_iswhite (line [i ])) {} 2038i ++ ; 2039 2040// Skip to before the middle leader 2041i -= middle_len ; 2042 2043// Check some expected things before we go on 2044if (i >=0 && end_len > 0 2045&& (uint8_t )lead_end [end_len - 1 ]== Ins .end_comment_pending ) { 2046// Backspace over all the stuff we want to replace 2047backspace_until_column (i ); 2048 2049// Insert the end-comment string, except for the last 2050// character, which will get inserted as normal later. 2051ins_bytes_len (lead_end , (size_t )(end_len - 1 )); 2052 } 2053 } 2054 } 2055Ins .end_comment_pending = NUL ; 2056 2057Ins .did_ai = false; 2058Ins .did_si = false; 2059Ins .can_si = false; 2060Ins .can_si_back = false; 2061 2062// If there's any pending input, grab up to INPUT_BUFLEN at once. 2063// This speeds up normal text input considerably. 2064// Don't do this when 'cindent' or 'indentexpr' is set, because we might 2065// need to re-indent at a ':', or any other character (but not what 2066// 'paste' is set).. 2067// Don't do this when there an InsertCharPre autocommand is defined, 2068// because we need to fire the event for every character. 2069// Do the check for InsertCharPre before the call to vpeekc() because the 2070// InsertCharPre autocommand could change the input buffer. 2071if (!ISSPECIAL (c ) 2072&& (utf_char2len (c )== 1 ) 2073&& !has_event (EVENT_INSERTCHARPRE ) 2074&& !test_disable_char_avail 2075&& vpeekc ()!= NUL 2076&& !(State & REPLACE_FLAG ) 2077&& !cindent_on () 2078&& !p_ri ) { 2079#define INPUT_BUFLEN 100 2080char buf [INPUT_BUFLEN + 1 ]; 2081colnr_T virtcol = 0 ; 2082 2083buf [0 ]= (char )c ; 2084int i = 1 ; 2085if (textwidth > 0 ) { 2086virtcol = get_nolist_virtcol (); 2087 } 2088// Stop the string when: 2089// - no more chars available 2090// - finding a special character (command key) 2091// - buffer is full 2092// - running into the 'textwidth' boundary 2093// - need to check for abbreviation: A non-word char after a word-char 2094while ((c = vpeekc ())!= NUL 2095&& !ISSPECIAL (c ) 2096&& MB_BYTE2LEN (c )== 1 2097&& i < INPUT_BUFLEN 2098&& (textwidth == 0 2099|| (virtcol += ascii2cells ((uint8_t )buf [i - 1 ]))< (colnr_T )textwidth ) 2100&& !(!no_abbr && !vim_iswordc (c )&& vim_iswordc ((uint8_t )buf [i - 1 ]))) { 2101c = vgetc (); 2102buf [i ++ ]= (char )c ; 2103 } 2104 2105do_digraph (-1 );// clear digraphs 2106do_digraph ((uint8_t )buf [i - 1 ]);// may be the start of a digraph 2107buf [i ]= NUL ; 2108ins_str (buf , (size_t )i ); 2109if (flags & INSCHAR_CTRLV ) { 2110redo_literal ((uint8_t )(* buf )); 2111i = 1 ; 2112 }else { 2113i = 0 ; 2114 } 2115if (buf [i ]!= NUL ) { 2116redo_append_lit (buf + i ,-1 ); 2117 } 2118 }else { 2119int cc ; 2120 2121if ((cc = utf_char2len (c ))> 1 ) { 2122char buf [MB_MAXCHAR + 1 ]; 2123 2124utf_char2bytes (c ,buf ); 2125buf [cc ]= NUL ; 2126ins_char_bytes (buf , (size_t )cc ); 2127redo_append_char (c ); 2128 }else { 2129ins_char (c ); 2130if (flags & INSCHAR_CTRLV ) { 2131redo_literal (c ); 2132 }else { 2133redo_append_char (c ); 2134 } 2135 } 2136 } 2137} 2138 2139// Put a character in the redo buffer, for when just after a CTRL-V. 2140static void redo_literal (int c ) 2141{ 2142char buf [10 ]; 2143 2144// Only digits need special treatment. Translate them into a string of 2145// three digits. 2146if (ascii_isdigit (c )) { 2147vim_snprintf (buf ,sizeof (buf ),"%03d" ,c ); 2148redo_append_str (buf ,-1 ); 2149 }else { 2150redo_append_char (c ); 2151 } 2152} 2153 2154/// Called when the cursor moves in insert-mode without editing text (arrow keys, <Home>, mouse). 2155/// For undo/redo it resembles hitting the <ESC> key. 2156/// 2157/// @param end_insert_pos Can be NULL 2158/// @param end_change End undoable change 2159/// @param move_key Cursor-move key, captured in the CmdAtom (replayed at mc-cascade). 2160/// NUL for non-captured jumps (mouse, <PageUp>, <C-Home>); then the next 2161/// edit restarts a new insert-session (stop_arrow()). 2162void start_arrow (pos_T * end_insert_pos ,bool end_change ,int move_key ) 2163{ 2164if (Ins .moved == kInsNone && end_change ) {// something has been inserted 2165stop_insert (end_insert_pos , false, false);// this stops the current insert 2166 } 2167if (Ins .moved != kInsJump ) { 2168if (move_key == NUL ) { 2169redo_append_str (S_LEN (ESC_STR )); 2170Ins .moved = kInsJump ; 2171 }else { 2172if (!IS_SPECIAL (move_key )) { 2173// CTRL-G j/k: the only captured cursor-moves typed as plain chars. 2174redo_append_char (Ctrl_G ); 2175 } 2176redo_append_char (move_key ); 2177if (end_change ) { 2178Ins .moved = kInsArrow ; 2179 } 2180 } 2181 } 2182check_spell_redraw (); 2183} 2184 2185/// Like start_arrow(); if `end_change` is false (CTRL-G U pending), also captures the CTRL-G U 2186/// keys in the atom, ahead of "move_key": replay re-executes the whole "<C-g>U<Left>". 2187/// 2188/// (Capturing them here, before start_arrow(), cannot corrupt stop_insert()'s last_insert 2189/// harvest: they append only when "end_change" is false, and stop_insert() runs only when it 2190/// is true.) 2191/// 2192/// @param end_insert_pos Can be NULL 2193/// @param end_change End undoable change 2194/// @param move_key @see start_arrow() 2195static void start_arrow_with_change (pos_T * end_insert_pos ,bool end_change ,int move_key ) 2196{ 2197if (!end_change && Ins .moved != kInsJump ) { 2198redo_append_char (Ctrl_G ); 2199redo_append_char ('U' ); 2200 } 2201start_arrow (end_insert_pos ,end_change ,move_key ); 2202} 2203 2204// If we skipped highlighting word at cursor, do it now. 2205// It may be skipped again, thus reset spell_redraw_lnum first. 2206static void check_spell_redraw (void ) 2207{ 2208if (spell_redraw_lnum != 0 ) { 2209linenr_T lnum = spell_redraw_lnum ; 2210 2211spell_redraw_lnum = 0 ; 2212redrawWinline (curwin ,lnum ); 2213 } 2214} 2215 2216// stop_arrow() is called before a change is made in insert mode. 2217// 2218// After a cursor-move (`Ins.moved`), the change starts a new INSERTION (see `Ins.start`). 2219// Returns FAIL if undo is impossible, shouldn't insert then. 2220int stop_arrow (void ) 2221{ 2222if (Ins .moved != kInsNone ) { 2223Ins .start = curwin -> w_cursor ;// new insertion starts here 2224if (Ins .start .col > Ins .start_orig .col && !Ins .need_undo ) { 2225// Don't update the original insert position when moved to the 2226// right, except when nothing was inserted yet. 2227Ins .update_start_orig = false; 2228 } 2229Ins .start_textlen = linetabsize_str (get_cursor_line_ptr ()); 2230 2231const bool jumped = Ins .moved == kInsJump ; 2232if (u_save_cursor ()== OK ) { 2233Ins .moved = kInsNone ; 2234Ins .need_undo = false; 2235 } 2236Ins .ai_col = 0 ; 2237if (State & VREPLACE_FLAG ) { 2238orig_line_count = curbuf -> b_ml .ml_line_count ; 2239vr_lines_changed = 1 ; 2240 } 2241if (jumped ) { 2242// Non-captured cursor-move (mouse, <PageUp>, …): restart the capture as a "1i" insertion. 2243// The count is a spec field (not body bytes), so "[count]." replaces it ("3i…"). 2244prep_redo (false, false, (CmdSpec ){ .count = 1 , .cmd = 'i' }); 2245Ins .new_insert_skip = 2 ; 2246mc_ins_cascade_restart (); 2247 }else { 2248// Cursor-move was captured (start_arrow()): the atom mc-cascade will replay it. 2249// Only `last_insert` (the ". register, i_CTRL-A) restarts here, like Vim. 2250String redo = redo_keys (NULL ); 2251Ins .new_insert_skip = (int )redo .size ; 2252xfree (redo .data ); 2253 } 2254 }else if (Ins .need_undo ) { 2255if (u_save_cursor ()== OK ) { 2256// A command or event may have moved the cursor before the next 2257// edit. Pull Ins.start back only when the cursor moved above it, 2258// so that later edits can properly decide whether an extra undo 2259// entry is needed. Advancing Ins.start would mis-place '[ after a 2260// register paste. 2261if (lt (curwin -> w_cursor ,Ins .start )) { 2262Ins .start = curwin -> w_cursor ; 2263Ins .start_textlen = (colnr_T )linetabsize_str (get_cursor_line_ptr ()); 2264 } 2265Ins .need_undo = false; 2266 } 2267 } 2268 2269// Always open fold at the cursor line when inserting something. 2270foldOpenCursor (); 2271 2272return Ins .moved != kInsNone || Ins .need_undo ?FAIL :OK ; 2273} 2274 2275/// Do a few things to stop inserting. 2276/// "end_insert_pos" is where insert ended. It is NULL when we already jumped 2277/// to another window/buffer. 2278/// 2279/// @param esc called by ins_esc() 2280/// @param nomove <c-\><c-o>, don't move cursor 2281static void stop_insert (pos_T * end_insert_pos ,int esc ,int nomove ) 2282{ 2283stop_redo_ins (); 2284kv_destroy (replace_stack );// abandon replace stack (reinitializes) 2285 2286// Save the inserted text for later redo with ^@ and CTRL-A. 2287// Don't do it when "restart_edit" was set and nothing was inserted, 2288// otherwise CTRL-O w and then <Left> will clear "last_insert". 2289String redo = redo_keys (NULL ); 2290int added = redo .data == NULL ?0 : (int )redo .size - Ins .new_insert_skip ; 2291if (Ins .did_restart_edit == 0 || added > 0 ) { 2292xfree (last_insert .data ); 2293last_insert = redo ;// structure copy 2294last_insert_skip = added < 0 ?0 :Ins .new_insert_skip ; 2295 }else { 2296xfree (redo .data ); 2297 } 2298 2299if (Ins .moved == kInsNone && end_insert_pos != NULL ) { 2300int cc ; 2301// Auto-format now. It may seem strange to do this when stopping an 2302// insertion (or moving the cursor), but it's required when appending 2303// a line and having it end in a space. But only do it when something 2304// was actually inserted, otherwise undo won't work. 2305if (!Ins .need_undo && has_format_option (kFoAuto )) { 2306pos_T tpos = curwin -> w_cursor ; 2307 2308// When the cursor is at the end of the line after a space the 2309// formatting will move it to the following word. Avoid that by 2310// moving the cursor onto the space. 2311cc = 'x' ; 2312if (curwin -> w_cursor .col > 0 && gchar_cursor ()== NUL ) { 2313dec_cursor (); 2314cc = gchar_cursor (); 2315if (!ascii_iswhite (cc )) { 2316curwin -> w_cursor = tpos ; 2317 } 2318 } 2319 2320auto_format (true, false); 2321 2322if (ascii_iswhite (cc )) { 2323if (gchar_cursor ()!= NUL ) { 2324inc_cursor (); 2325 } 2326// If the cursor is still at the same character, also keep 2327// the "coladd". 2328if (gchar_cursor ()== NUL 2329&& curwin -> w_cursor .lnum == tpos .lnum 2330&& curwin -> w_cursor .col == tpos .col ) { 2331curwin -> w_cursor .coladd = tpos .coladd ; 2332 } 2333 } 2334 } 2335 2336// If a space was inserted for auto-formatting, remove it now. 2337check_auto_format (true); 2338 2339// If we just did an auto-indent, remove the whitespace from EOL, and put the cursor back. 2340// Do this when ESC was used or moving the cursor up/down. 2341// Check for the old position still being valid, just in case the text changed unexpectedly. 2342// Not for span replay during a mc-session: its synthetic <Esc> ends the nested session early. 2343if (!nomove && Ins .did_ai && !mc_ins_replaying () 2344&& (esc || (vim_strchr (p_cpo ,kCpoIndent )== NULL 2345&& curwin -> w_cursor .lnum != end_insert_pos -> lnum )) 2346&& end_insert_pos -> lnum <=curbuf -> b_ml .ml_line_count ) { 2347pos_T tpos = curwin -> w_cursor ; 2348colnr_T prev_col = end_insert_pos -> col ; 2349 2350curwin -> w_cursor = * end_insert_pos ; 2351check_cursor_col (curwin );// make sure it is not past the line 2352 2353// Where the loop would actually start (back up if NUL). 2354colnr_T strip_col = curwin -> w_cursor .col ; 2355if (gchar_cursor ()== NUL && strip_col > 0 ) { 2356strip_col -- ; 2357 } 2358 2359// Don't strip if non-whitespace follows: setline() from a <Cmd> 2360// mapping or CursorHoldI autocmd may have inserted content. 2361if (* skipwhite (get_cursor_line_ptr ()+ strip_col )== NUL ) { 2362curwin -> w_cursor .col = strip_col ; 2363while (true) { 2364if (gchar_cursor ()== NUL && curwin -> w_cursor .col > 0 ) { 2365curwin -> w_cursor .col -- ; 2366 } 2367cc = gchar_cursor (); 2368if (!ascii_iswhite (cc )) { 2369break ; 2370 } 2371if (del_char (true)== FAIL ) { 2372break ;// should not happen 2373 } 2374 } 2375if (curwin -> w_cursor .lnum != tpos .lnum ) { 2376curwin -> w_cursor = tpos ; 2377 }else if (curwin -> w_cursor .col < prev_col ) { 2378// reset tpos, could have been invalidated in the loop above 2379tpos = curwin -> w_cursor ; 2380tpos .col ++ ; 2381if (cc != NUL && gchar_pos (& tpos )== NUL ) { 2382curwin -> w_cursor .col ++ ;// put cursor back on the NUL 2383 } 2384 } 2385 2386// <C-S-Right> may have started Visual mode, adjust the position for 2387// deleted characters. 2388if (Visual .active ) { 2389check_visual_pos (); 2390 } 2391 }else { 2392// Non-whitespace follows, keep original cursor. 2393curwin -> w_cursor = tpos ; 2394 } 2395 } 2396 } 2397Ins .did_ai = false; 2398Ins .did_si = false; 2399Ins .can_si = false; 2400Ins .can_si_back = false; 2401 2402// Set '[ and '] to the inserted text. When end_insert_pos is NULL we are 2403// now in a different buffer. 2404if (end_insert_pos != NULL ) { 2405curbuf -> b_op_start = Ins .start ; 2406curbuf -> b_op_start_orig = Ins .start_orig ; 2407curbuf -> b_op_end = * end_insert_pos ; 2408 } 2409} 2410 2411// Set the last inserted text to a single character. 2412// Used for the replace command. 2413void set_last_insert (int c ) 2414{ 2415xfree (last_insert .data ); 2416last_insert .data = xmalloc (MB_MAXBYTES * 3 + 5 ); 2417char * s = last_insert .data ; 2418// Use the CTRL-V only when entering a special char 2419if (c < ' ' || c == DEL ) { 2420* s ++ = Ctrl_V ; 2421 } 2422s = add_char2buf (c ,s ); 2423* s ++ = ESC ; 2424* s = NUL ; 2425last_insert .size = (size_t )(s - last_insert .data ); 2426last_insert_skip = 0 ; 2427} 2428 2429#ifdef EXITFREE 2430void free_last_insert (void ) 2431{ 2432API_CLEAR_STRING (last_insert ); 2433} 2434#endif 2435 2436// move cursor to start of line 2437// if flags & BL_WHITE move to first non-white 2438// if flags & BL_SOL move to first non-white if startofline is set, 2439// otherwise keep "curswant" column 2440// if flags & BL_FIX don't leave the cursor on a NUL. 2441void beginline (int flags ) 2442{ 2443if ((flags & BL_SOL )&& !p_sol ) { 2444coladvance (curwin ,curwin -> w_curswant ); 2445 }else { 2446curwin -> w_cursor .col = 0 ; 2447curwin -> w_cursor .coladd = 0 ; 2448 2449if (flags & (BL_WHITE |BL_SOL )) { 2450for (char * ptr = get_cursor_line_ptr ();ascii_iswhite (* ptr ) 2451&& !((flags & BL_FIX )&& ptr [1 ]== NUL );ptr ++ ) { 2452curwin -> w_cursor .col ++ ; 2453 } 2454 } 2455curwin -> w_set_curswant = true; 2456 } 2457adjust_skipcol (); 2458} 2459 2460// oneright oneleft cursor_down cursor_up 2461// 2462// Move one char {right,left,down,up}. 2463// Doesn't move onto the NUL past the end of the line, unless it is allowed. 2464// Return OK when successful, FAIL when we hit a line of file boundary. 2465 2466int oneright (void ) 2467{ 2468char * ptr ; 2469 2470if (virtual_active (curwin )) { 2471pos_T prevpos = curwin -> w_cursor ; 2472 2473// Adjust for multi-wide char (excluding TAB) 2474ptr = get_cursor_pos_ptr (); 2475coladvance (curwin ,getviscol ()+ ((* ptr != TAB && vim_isprintc (utf_ptr2char (ptr ))) 2476 ?ptr2cells (ptr ) :1 )); 2477curwin -> w_set_curswant = true; 2478// Return OK if the cursor moved, FAIL otherwise (at window edge). 2479return (prevpos .col != curwin -> w_cursor .col 2480|| prevpos .coladd != curwin -> w_cursor .coladd ) ?OK :FAIL ; 2481 } 2482 2483ptr = get_cursor_pos_ptr (); 2484if (* ptr == NUL ) { 2485return FAIL ;// already at the very end 2486 } 2487 2488int l = utfc_ptr2len (ptr ); 2489 2490// move "l" bytes right, but don't end up on the NUL, unless 'virtualedit' 2491// contains "onemore". 2492if (ptr [l ]== NUL && (get_ve_flags (curwin )& kOptVeFlagOnemore )== 0 ) { 2493return FAIL ; 2494 } 2495curwin -> w_cursor .col += l ; 2496 2497curwin -> w_set_curswant = true; 2498adjust_skipcol (); 2499return OK ; 2500} 2501 2502int oneleft (void ) 2503{ 2504if (virtual_active (curwin )) { 2505int v = getviscol (); 2506 2507if (v == 0 ) { 2508return FAIL ; 2509 } 2510 2511// We might get stuck on 'showbreak', skip over it. 2512int width = 1 ; 2513while (true) { 2514coladvance (curwin ,v - width ); 2515// getviscol() is slow, skip it when 'showbreak' is empty, 2516// 'breakindent' is not set and there are no multi-byte 2517// characters 2518if (getviscol ()< v ) { 2519break ; 2520 } 2521width ++ ; 2522 } 2523 2524if (curwin -> w_cursor .coladd == 1 ) { 2525// Adjust for multi-wide char (not a TAB) 2526char * ptr = get_cursor_pos_ptr (); 2527if (* ptr != TAB && vim_isprintc (utf_ptr2char (ptr ))&& ptr2cells (ptr )> 1 ) { 2528curwin -> w_cursor .coladd = 0 ; 2529 } 2530 } 2531 2532curwin -> w_set_curswant = true; 2533adjust_skipcol (); 2534return OK ; 2535 } 2536 2537if (curwin -> w_cursor .col == 0 ) { 2538return FAIL ; 2539 } 2540 2541curwin -> w_set_curswant = true; 2542curwin -> w_cursor .col -- ; 2543 2544// if the character on the left of the current cursor is a multi-byte 2545// character, move to its first byte 2546mb_adjust_cursor (); 2547adjust_skipcol (); 2548return OK ; 2549} 2550 2551/// Move the cursor up "n" lines in window "wp". Takes care of closed folds. 2552/// Skips over concealed lines when "skip_conceal" is true. 2553void cursor_up_inner (win_T * wp ,linenr_T n ,bool skip_conceal ) 2554{ 2555linenr_T lnum = wp -> w_cursor .lnum ; 2556 2557if (n >=lnum ) { 2558lnum = 1 ; 2559 }else if (win_lines_concealed (wp )) { 2560// Count each sequence of folded lines as one logical line. 2561 2562// go to the start of the current fold 2563hasFolding (wp ,lnum ,& lnum ,NULL ); 2564 2565while (n -- ) { 2566// move up one line 2567lnum -- ; 2568if (lnum <=1 ) { 2569break ; 2570 } 2571n += skip_conceal && decor_conceal_line (wp ,lnum - 1 , true); 2572// If we entered a fold, move to the beginning, unless in 2573// Insert mode or when 'foldopen' contains "all": it will open 2574// in a moment. 2575if (n > 0 || !((State & MODE_INSERT )|| (fdo_flags & kOptFdoFlagAll ))) { 2576hasFolding (wp ,lnum ,& lnum ,NULL ); 2577 } 2578 } 2579lnum = MAX (lnum ,1 ); 2580 }else { 2581lnum -= n ; 2582 } 2583 2584wp -> w_cursor .lnum = lnum ; 2585} 2586 2587/// @param upd_topline When true: update topline 2588int cursor_up (linenr_T n ,bool upd_topline ) 2589{ 2590// This fails if the cursor is already in the first line. 2591if (n > 0 && curwin -> w_cursor .lnum <=1 ) { 2592return FAIL ; 2593 } 2594cursor_up_inner (curwin ,n , false); 2595 2596// try to advance to the column we want to be at 2597coladvance (curwin ,curwin -> w_curswant ); 2598 2599if (upd_topline ) { 2600update_topline (curwin );// make sure curwin->w_topline is valid 2601 } 2602 2603return OK ; 2604} 2605 2606/// Move the cursor down "n" lines in window "wp". Takes care of closed folds. 2607/// Skips over concealed lines when "skip_conceal" is true. 2608void cursor_down_inner (win_T * wp ,int n ,bool skip_conceal ) 2609{ 2610linenr_T lnum = wp -> w_cursor .lnum ; 2611linenr_T line_count = wp -> w_buffer -> b_ml .ml_line_count ; 2612 2613if (lnum + n >=line_count ) { 2614lnum = line_count ; 2615 }else if (win_lines_concealed (wp )) { 2616linenr_T last ; 2617 2618// count each sequence of folded lines as one logical line 2619while (n -- ) { 2620if (hasFoldingWin (wp ,lnum ,NULL ,& last , true,NULL )) { 2621lnum = last + 1 ; 2622 }else { 2623lnum ++ ; 2624 } 2625if (lnum >=line_count ) { 2626break ; 2627 } 2628n += skip_conceal && decor_conceal_line (wp ,lnum - 1 , true); 2629 } 2630lnum = MIN (lnum ,line_count ); 2631 }else { 2632lnum += (linenr_T )n ; 2633 } 2634 2635wp -> w_cursor .lnum = lnum ; 2636} 2637 2638/// @param upd_topline When true: update topline 2639int cursor_down (int n ,bool upd_topline ) 2640{ 2641linenr_T lnum = curwin -> w_cursor .lnum ; 2642// This fails if the cursor is already in the last (folded) line. 2643hasFoldingWin (curwin ,lnum ,NULL ,& lnum , true,NULL ); 2644if (n > 0 && lnum >=curwin -> w_buffer -> b_ml .ml_line_count ) { 2645return FAIL ; 2646 } 2647cursor_down_inner (curwin ,n , false); 2648 2649// try to advance to the column we want to be at 2650coladvance (curwin ,curwin -> w_curswant ); 2651 2652if (upd_topline ) { 2653update_topline (curwin );// make sure curwin->w_topline is valid 2654 } 2655 2656return OK ; 2657} 2658 2659/// Stuff the last inserted text in the read buffer. 2660/// Last_insert actually is a copy of the redo buffer, so we 2661/// first have to remove the command. 2662/// 2663/// @param c Command character to be inserted 2664/// @param count Repeat this many times 2665/// @param no_esc Don't add an ESC at the end 2666int stuff_inserted (int c ,int count ,int no_esc ) 2667{ 2668char last = NUL ; 2669 2670String insert = get_last_insert ();// text to be inserted 2671if (insert .data == NULL ) { 2672emsg (_ (e_noinstext )); 2673return FAIL ; 2674 } 2675 2676// may want to stuff the command character, to start Insert mode 2677if (c != NUL ) { 2678stuffcharReadbuff (c ); 2679 } 2680 2681if (insert .size > 0 ) { 2682// look for the last ESC in 'insert' 2683for (char * p = insert .data + insert .size - 1 ;p >=insert .data ;p -- ) { 2684if (* p == ESC ) { 2685insert .size = (size_t )(p - insert .data ); 2686break ; 2687 } 2688 } 2689 } 2690 2691if (insert .size > 0 ) { 2692char * p = insert .data + insert .size - 1 ; 2693// when the last char is either "0" or "^" it will be quoted if no ESC 2694// comes after it OR if it will inserted more than once and "ptr" 2695// starts with ^D. -- Acevedo 2696if ((* p == '0' || * p == '^' ) 2697&& (no_esc || (* insert .data == Ctrl_D && count > 1 ))) { 2698last = * p ; 2699insert .size -- ; 2700 } 2701 } 2702 2703do { 2704stuffReadbuffLen (insert .data , (ptrdiff_t )insert .size ); 2705// A trailing "0" is inserted as "<C-V>048", "^" as "<C-V>^". 2706switch (last ) { 2707case '0' : 2708stuffReadbuffLen (S_LEN ("\026\060\064\070" )); 2709break ; 2710case '^' : 2711stuffReadbuffLen (S_LEN ("\026^" )); 2712break ; 2713default : 2714break ; 2715 } 2716 }while (-- count > 0 ); 2717 2718// may want to stuff a trailing ESC, to get out of Insert mode 2719if (!no_esc ) { 2720stuffcharReadbuff (ESC ); 2721 } 2722 2723return OK ; 2724} 2725 2726String get_last_insert (void ) 2727FUNC_ATTR_PURE 2728{ 2729return last_insert .data == NULL ?NULL_STRING : (String ){ 2730 .data = last_insert .data + last_insert_skip , 2731 .size = last_insert .size - (size_t )last_insert_skip , 2732 }; 2733} 2734 2735// Get last inserted string, and remove trailing <Esc>. 2736// Returns pointer to allocated memory (must be freed) or NULL. 2737char * get_last_insert_save (void ) 2738{ 2739String insert = get_last_insert (); 2740 2741if (insert .data == NULL ) { 2742return NULL ; 2743 } 2744 2745char * s = xmemdupz (insert .data ,insert .size ); 2746if (insert .size > 0 && s [insert .size - 1 ]== ESC ) {// remain trailing ESC 2747s [-- insert .size ]= NUL ; 2748 } 2749return s ; 2750} 2751 2752/// Check the word in front of the cursor for an abbreviation. 2753/// Called when the non-id character "c" has been entered. 2754/// When an abbreviation is recognized it is removed from the text and 2755/// the replacement string is inserted in typebuf.tb_buf[], followed by "c". 2756/// 2757/// @param c character 2758/// 2759/// @return true if the word is a known abbreviation. 2760static bool echeck_abbr (int c ) 2761FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 2762{ 2763// Don't check for abbreviation in paste mode, when disabled and just 2764// after moving around with cursor keys. 2765if (p_paste || no_abbr || Ins .moved != kInsNone ) { 2766return false; 2767 } 2768 2769return check_abbr (c ,get_cursor_line_ptr (),curwin -> w_cursor .col , 2770curwin -> w_cursor .lnum == Ins .start .lnum ?Ins .start .col :0 ); 2771} 2772 2773// replace-stack functions 2774// 2775// When replacing characters, the replaced characters are remembered for each 2776// new character. This is used to re-insert the old text when backspacing. 2777// 2778// There is a NUL headed list of characters for each character that is 2779// currently in the file after the insertion point. When BS is used, one NUL 2780// headed list is put back for the deleted character. 2781// 2782// For a newline, there are two NUL headed lists. One contains the characters 2783// that the NL replaced. The extra one stores the characters after the cursor 2784// that were deleted (always white space). 2785 2786/// Push character that is replaced onto the replace stack. 2787/// 2788/// replace_offset is normally 0, in which case replace_push will add a new 2789/// character at the end of the stack. If replace_offset is not 0, that many 2790/// characters will be left on the stack above the newly inserted character. 2791/// 2792/// @param str character that is replaced (NUL is none) 2793/// @param len length of character in bytes 2794void replace_push (char * str ,size_t len ) 2795{ 2796// TODO(bfredl): replace_offset is suss af, if we don't need it, this 2797// function is just kv_concat() :p 2798if (kv_size (replace_stack )< (size_t )replace_offset ) {// nothing to do 2799return ; 2800 } 2801 2802kv_ensure_space (replace_stack ,len ); 2803 2804char * p = replace_stack .items + kv_size (replace_stack )- replace_offset ; 2805if (replace_offset ) { 2806memmove (p + len ,p , (size_t )replace_offset ); 2807 } 2808memcpy (p ,str ,len ); 2809kv_size (replace_stack )+= len ; 2810} 2811 2812/// push NUL as separator between entries in the stack 2813void replace_push_nul (void ) 2814{ 2815replace_push ("" ,1 ); 2816} 2817 2818/// Check top of replace stack, pop it if it was NUL 2819/// 2820/// when a non-NUL byte is found, use mb_replace_pop_ins() to 2821/// pop one complete multibyte character. 2822/// 2823/// @return -1 if stack is empty, last byte of char or NUL otherwise 2824static int replace_pop_if_nul (void ) 2825{ 2826int ch = (kv_size (replace_stack )) ? (uint8_t )kv_A (replace_stack ,kv_size (replace_stack )- 1 ) :-1 ; 2827if (ch == NUL ) { 2828kv_size (replace_stack )-- ; 2829 } 2830return ch ; 2831} 2832 2833/// Join the top two items on the replace stack. This removes to "off"'th NUL 2834/// encountered. 2835/// 2836/// @param off offset for which NUL to remove 2837void replace_join (int off ) 2838{ 2839for (ssize_t i = (ssize_t )kv_size (replace_stack );-- i >=0 ;) { 2840if (kv_A (replace_stack ,i )== NUL && off -- <=0 ) { 2841kv_size (replace_stack )-- ; 2842memmove (& kv_A (replace_stack ,i ),& kv_A (replace_stack ,i + 1 ), 2843 (kv_size (replace_stack )- (size_t )i )); 2844return ; 2845 } 2846 } 2847} 2848 2849/// Pop bytes from the replace stack until a NUL is found, and insert them 2850/// before the cursor. Can only be used in MODE_REPLACE or MODE_VREPLACE state. 2851static void replace_pop_ins (void ) 2852{ 2853int oldState = State ; 2854 2855State = MODE_NORMAL ;// don't want MODE_REPLACE here 2856while ((replace_pop_if_nul ())> 0 ) { 2857mb_replace_pop_ins (); 2858dec_cursor (); 2859 } 2860State = oldState ; 2861} 2862 2863/// Insert multibyte char popped from the replace stack. 2864/// 2865/// caller must already have checked the top of the stack is not NUL!! 2866static void mb_replace_pop_ins (void ) 2867{ 2868int len = utf_head_off (& kv_A (replace_stack ,0 ), 2869& kv_A (replace_stack ,kv_size (replace_stack )- 1 ))+ 1 ; 2870kv_size (replace_stack )-= (size_t )len ; 2871ins_bytes_len (& kv_A (replace_stack ,kv_size (replace_stack )), (size_t )len ); 2872} 2873 2874// Handle doing a BS for one character. 2875// cc < 0: replace stack empty, just move cursor 2876// cc == 0: character was inserted, delete it 2877// cc > 0: character was replaced, put cc (first byte of original char) back 2878// and check for more characters to be put back 2879// When "limit_col" is >= 0, don't delete before this column. Matters when 2880// using composing characters, use del_char_after_col() instead of del_char(). 2881static void replace_do_bs (int limit_col ) 2882{ 2883colnr_T start_vcol ; 2884const int l_State = State ; 2885 2886int cc = replace_pop_if_nul (); 2887if (cc > 0 ) { 2888int orig_len = 0 ; 2889int orig_vcols = 0 ; 2890if (l_State & VREPLACE_FLAG ) { 2891// Get the number of screen cells used by the character we are 2892// going to delete. 2893getvcol (curwin ,& curwin -> w_cursor ,NULL ,& start_vcol ,NULL ,0 ); 2894orig_vcols = win_chartabsize (curwin ,get_cursor_pos_ptr (),start_vcol ); 2895 } 2896del_char_after_col (limit_col ); 2897if (l_State & VREPLACE_FLAG ) { 2898orig_len = get_cursor_pos_len (); 2899 } 2900replace_pop_ins (); 2901 2902if (l_State & VREPLACE_FLAG ) { 2903// Get the number of screen cells used by the inserted characters 2904char * p = get_cursor_pos_ptr (); 2905int ins_len = get_cursor_pos_len ()- orig_len ; 2906int vcol = start_vcol ; 2907for (int i = 0 ;i < ins_len ;i ++ ) { 2908vcol += win_chartabsize (curwin ,p + i ,vcol ); 2909i += utfc_ptr2len (p + i )- 1 ; 2910 } 2911vcol -= start_vcol ; 2912 2913// Delete spaces that were inserted after the cursor to keep the 2914// text aligned. 2915curwin -> w_cursor .col += ins_len ; 2916while (vcol > orig_vcols && gchar_cursor ()== ' ' ) { 2917del_char (false); 2918orig_vcols ++ ; 2919 } 2920curwin -> w_cursor .col -= ins_len ; 2921 } 2922 2923// mark the buffer as changed and prepare for displaying 2924changed_bytes (curwin -> w_cursor .lnum ,curwin -> w_cursor .col ); 2925 }else if (cc == 0 ) { 2926del_char_after_col (limit_col ); 2927 } 2928} 2929 2930static void ins_reg (void ) 2931{ 2932bool need_redraw = false; 2933int literally = 0 ; 2934int vis_active = Visual .active ; 2935 2936// If we are going to wait for a character, show a '"'. 2937pc_status = PC_STATUS_UNSET ; 2938if (redrawing ()&& !char_avail ()) { 2939// may need to redraw when no more chars available now 2940ins_redraw (false); 2941 2942edit_putchar ('"' , true); 2943add_to_showcmd_c (Ctrl_R ); 2944 } 2945 2946// Don't map the register name. This also prevents the mode message to be 2947// deleted when ESC is hit. 2948no_mapping ++ ; 2949allow_keys ++ ; 2950int regname = plain_vgetc (); 2951LANGMAP_ADJUST (regname , true); 2952if (regname == Ctrl_R || regname == Ctrl_O || regname == Ctrl_P ) { 2953// Get a third key for literal register insertion 2954literally = regname ; 2955add_to_showcmd_c (literally ); 2956regname = plain_vgetc (); 2957LANGMAP_ADJUST (regname , true); 2958 } 2959no_mapping -- ; 2960allow_keys -- ; 2961 2962// Don't call u_sync() while typing the expression or giving an error 2963// message for it. Only call it explicitly. 2964no_u_sync ++ ; 2965if (regname == '=' ) { 2966pos_T curpos = curwin -> w_cursor ; 2967 2968// Sync undo when evaluating the expression calls setline() or 2969// append(), so that it can be undone separately. 2970u_sync_once = 2 ; 2971 2972regname = get_expr_register (); 2973 2974// Cursor may be moved back a column. 2975curwin -> w_cursor = curpos ; 2976check_cursor (curwin ); 2977 } 2978if (regname == NUL || !valid_yank_reg (regname , false)) { 2979vim_beep (kOptBoFlagRegister ); 2980need_redraw = true;// remove the '"' 2981 }else { 2982yankreg_T * reg = get_yank_register (regname ,YREG_PASTE ); 2983 2984if (literally == Ctrl_O || literally == Ctrl_P ) { 2985// Append the command to the redo buffer. 2986redo_append_char (Ctrl_R ); 2987redo_append_char (literally ); 2988redo_append_char (regname ); 2989 2990do_put (regname ,NULL ,BACKWARD ,1 , 2991 (literally == Ctrl_P ?PUT_FIXINDENT :0 ) |PUT_CURSEND ); 2992 }else if (reg -> y_size > 1 && is_literal_register (regname )) { 2993redo_append_char (Ctrl_R ); 2994redo_append_char (regname ); 2995do_put (regname ,NULL ,BACKWARD ,1 ,PUT_CURSEND ); 2996 }else if (insert_reg (regname ,NULL , !!literally )== FAIL ) { 2997vim_beep (kOptBoFlagRegister ); 2998need_redraw = true;// remove the '"' 2999 }else if (Ins .stop_insert_mode ) { 3000// When the '=' register was used and a function was invoked that 3001// did ":stopinsert" then stuff_empty() returns false but we won't 3002// insert anything, need to remove the '"' 3003need_redraw = true; 3004 } 3005 } 3006no_u_sync -- ; 3007if (u_sync_once == 1 ) { 3008Ins .need_undo = true; 3009 } 3010u_sync_once = 0 ; 3011 3012// If the inserted register is empty, we need to remove the '"'. Do this before 3013// clearing showcmd, which emits an event that can also update the screen. 3014if (need_redraw || stuff_empty ()) { 3015edit_unputchar (); 3016 } 3017clear_showcmd (); 3018 3019// Disallow starting Visual mode here, would get a weird mode. 3020if (!vis_active && Visual .active ) { 3021end_visual_mode (); 3022 } 3023} 3024 3025// CTRL-G commands in Insert mode. 3026static void ins_ctrl_g (void ) 3027{ 3028// Right after CTRL-X the cursor will be after the ruler. 3029setcursor (); 3030 3031// Don't map the second key. This also prevents the mode message to be 3032// deleted when ESC is hit. 3033no_mapping ++ ; 3034allow_keys ++ ; 3035int c = plain_vgetc (); 3036no_mapping -- ; 3037allow_keys -- ; 3038switch (c ) { 3039// CTRL-G k and CTRL-G <Up>: cursor up to Ins.start.col 3040case K_UP : 3041case Ctrl_K : 3042case 'k' : 3043ins_up (true); 3044break ; 3045 3046// CTRL-G j and CTRL-G <Down>: cursor down to Ins.start.col 3047case K_DOWN : 3048case Ctrl_J : 3049case 'j' : 3050ins_down (true); 3051break ; 3052 3053// CTRL-G u: start new undoable edit 3054case 'u' : 3055u_sync (true); 3056Ins .need_undo = true; 3057 3058// Need to reset Ins.start, esp. because a BS that joins 3059// a line to the previous one must save for undo. 3060Ins .update_start_orig = false; 3061Ins .start = curwin -> w_cursor ; 3062break ; 3063 3064// CTRL-G U: do not break undo with the next char. 3065case 'U' : 3066// Allow one left/right cursor movement with the next char, 3067// without breaking undo. 3068Ins .dont_sync_undo = kNone ; 3069break ; 3070 3071case ESC : 3072// Esc after CTRL-G cancels it. 3073break ; 3074 3075// Unknown CTRL-G command, reserved for future expansion. 3076default : 3077vim_beep (kOptBoFlagCtrlg ); 3078 } 3079} 3080 3081// CTRL-^ in Insert mode. 3082static void ins_ctrl_hat (void ) 3083{ 3084if (map_to_exists_mode ("" ,MODE_LANGMAP , false)) { 3085// ":lmap" mappings exists, Toggle use of ":lmap" mappings. 3086if (State & MODE_LANGMAP ) { 3087curbuf -> b_p_iminsert = B_IMODE_NONE ; 3088State &= ~MODE_LANGMAP ; 3089 }else { 3090curbuf -> b_p_iminsert = B_IMODE_LMAP ; 3091State |=MODE_LANGMAP ; 3092 } 3093 } 3094set_iminsert_global (curbuf ); 3095showmode (); 3096// Show/unshow value of 'keymap' in status lines. 3097status_redraw_curbuf (); 3098} 3099 3100/// Handle ESC in insert mode. 3101/// 3102/// @param[in,out] count repeat count of the insert command 3103/// @param cmdchar command that started the insert 3104/// @param nomove when true, don't move the cursor 3105/// 3106/// @return true when leaving insert mode, false when repeating the insert. 3107static bool ins_esc (int * count ,int cmdchar ,bool nomove ) 3108FUNC_ATTR_NONNULL_ARG (1 ) 3109{ 3110static bool disabled_redraw = false; 3111 3112check_spell_redraw (); 3113 3114int temp = curwin -> w_cursor .col ; 3115if (disabled_redraw ) { 3116RedrawingDisabled -- ; 3117disabled_redraw = false; 3118 } 3119if (Ins .moved == kInsNone ) { 3120// Don't append the ESC for "r<CR>" and "grx". 3121if (cmdchar != 'r' && cmdchar != 'v' ) { 3122redo_append_str (S_LEN (ESC_STR )); 3123 } 3124 3125// Repeating insert may take a long time. Check for 3126// interrupt now and then. 3127if (* count > 0 ) { 3128line_breakcheck (); 3129if (got_int ) { 3130* count = 0 ; 3131 } 3132 } 3133 3134if (--* count > 0 ) {// repeat what was typed 3135// Vi repeats the insert without replacing characters. 3136if (vim_strchr (p_cpo ,kCpoReplcnt )!= NULL ) { 3137State &= ~REPLACE_FLAG ; 3138 } 3139 3140start_redo_ins (); 3141if (cmdchar == 'r' || cmdchar == 'v' ) { 3142stuffRedoReadbuff (ESC_STR );// No ESC in redo buffer 3143 } 3144RedrawingDisabled ++ ; 3145disabled_redraw = true; 3146// Repeat the insert 3147return false; 3148 } 3149stop_insert (& curwin -> w_cursor , true,nomove ); 3150undisplay_dollar (); 3151 }else if (Ins .moved == kInsArrow && cmdchar != 'r' && cmdchar != 'v' ) { 3152// The session ended just after a cursor-move: close the atom, so the whole session (including 3153// cursor-move) replays. 3154redo_append_str (S_LEN (ESC_STR )); 3155 } 3156 3157if (cmdchar != 'r' && cmdchar != 'v' ) { 3158ins_apply_autocmds (EVENT_INSERTLEAVEPRE ); 3159 } 3160 3161// When an autoindent was removed, curswant stays after the 3162// indent 3163if (restart_edit == NUL && (colnr_T )temp == curwin -> w_cursor .col ) { 3164curwin -> w_set_curswant = true; 3165 } 3166 3167// Remember the last Insert position in the '^ mark. 3168if ((cmdmod .cmod_flags & CMOD_KEEPJUMPS )== 0 ) { 3169fmarkv_T view = mark_view_make (curwin ,curwin -> w_cursor ); 3170RESET_FMARK (& curbuf -> b_last_insert ,curwin -> w_cursor ,curbuf -> b_fnum ,view ); 3171 } 3172 3173// The cursor should end up on the last inserted character. 3174// Don't do it for CTRL-O, unless past the end of the line. 3175if (!nomove 3176&& (curwin -> w_cursor .col != 0 || curwin -> w_cursor .coladd > 0 ) 3177&& (restart_edit == NUL || (gchar_cursor ()== NUL && !Visual .active )) 3178&& !Ins .revins_on ) { 3179if (curwin -> w_cursor .coladd > 0 || get_ve_flags (curwin )== kOptVeFlagAll ) { 3180oneleft (); 3181if (restart_edit != NUL ) { 3182curwin -> w_cursor .coladd ++ ; 3183 } 3184 }else { 3185curwin -> w_cursor .col -- ; 3186curwin -> w_valid &= ~(VALID_WCOL |VALID_VIRTCOL ); 3187// Correct cursor for multi-byte character. 3188mb_adjust_cursor (); 3189 } 3190 } 3191 3192State = MODE_NORMAL ; 3193may_trigger_modechanged (); 3194// need to position cursor again when on a TAB and 3195// when on a char with inline virtual text 3196if (gchar_cursor ()== TAB || buf_meta_total (curbuf ,kMTMetaInline )> 0 ) { 3197curwin -> w_valid &= ~(VALID_WROW |VALID_WCOL |VALID_VIRTCOL ); 3198 } 3199 3200setmouse (); 3201ui_cursor_shape ();// may show different cursor shape 3202 3203// When recording or for CTRL-O, need to display the new mode. 3204// Otherwise remove the mode message. 3205if (reg_recording != 0 || restart_edit != NUL ) { 3206showmode (); 3207 }else if (p_smd && (got_int || !skip_showmode ()) 3208&& !(p_ch == 0 && !ui_has (kUIMessages ))) { 3209unshowmode (false); 3210 } 3211// Exit Insert mode 3212return true; 3213} 3214 3215// Toggle language: Ins.revins_on. 3216// Move to end of reverse inserted text. 3217static void ins_ctrl_ (void ) 3218{ 3219if (Ins .revins_on && Ins .revins_chars && Ins .revins_scol >=0 ) { 3220while (gchar_cursor ()!= NUL && Ins .revins_chars -- ) { 3221curwin -> w_cursor .col ++ ; 3222 } 3223 } 3224p_ri = !p_ri ; 3225Ins .revins_on = (State == MODE_INSERT && p_ri ); 3226if (Ins .revins_on ) { 3227Ins .revins_scol = curwin -> w_cursor .col ; 3228Ins .revins_legal ++ ; 3229Ins .revins_chars = 0 ; 3230undisplay_dollar (); 3231 }else { 3232Ins .revins_scol = -1 ; 3233 } 3234showmode (); 3235} 3236 3237/// If 'keymodel' contains "startsel", may start selection. 3238/// 3239/// @param c character to check 3240// 3241/// @return true when a CTRL-O and other keys stuffed. 3242static bool ins_start_select (int c ) 3243FUNC_ATTR_WARN_UNUSED_RESULT 3244{ 3245if (!km_startsel ) { 3246return false; 3247 } 3248switch (c ) { 3249case K_KHOME : 3250case K_KEND : 3251case K_PAGEUP : 3252case K_KPAGEUP : 3253case K_PAGEDOWN : 3254case K_KPAGEDOWN : 3255if (!(mod_mask & MOD_MASK_SHIFT )) { 3256break ; 3257 } 3258FALLTHROUGH ; 3259case K_S_LEFT : 3260case K_S_RIGHT : 3261case K_S_UP : 3262case K_S_DOWN : 3263case K_S_END : 3264case K_S_HOME : 3265// Start selection right away, the cursor can move with CTRL-O when 3266// beyond the end of the line. 3267start_selection (); 3268 3269// Execute the key in (insert) Select mode. 3270stuffcharReadbuff (Ctrl_O ); 3271if (mod_mask ) { 3272const char buf []= { (char )K_SPECIAL , (char )KS_MODIFIER , 3273 (char )(uint8_t )mod_mask ,NUL }; 3274stuffReadbuffLen (buf ,3 ); 3275 } 3276stuffcharReadbuff (c ); 3277return true; 3278 } 3279return false; 3280} 3281 3282// <Insert> key in Insert mode: toggle insert/replace mode. 3283static void ins_insert (int replaceState ) 3284{ 3285set_vim_var_string (VV_INSERTMODE , ((State & REPLACE_FLAG ) 3286 ?"i" 3287 :replaceState == MODE_VREPLACE ?"v" :"r" ),1 ); 3288ins_apply_autocmds (EVENT_INSERTCHANGE ); 3289if (State & REPLACE_FLAG ) { 3290State = MODE_INSERT | (State & MODE_LANGMAP ); 3291 }else { 3292State = replaceState | (State & MODE_LANGMAP ); 3293 } 3294may_trigger_modechanged (); 3295redo_append_char (K_INS ); 3296showmode (); 3297ui_cursor_shape ();// may show different cursor shape 3298} 3299 3300// Pressed CTRL-O in Insert mode. 3301static void ins_ctrl_o (void ) 3302{ 3303Visual .restart_select = 0 ; 3304if (State & VREPLACE_FLAG ) { 3305restart_edit = 'V' ; 3306 }else if (State & REPLACE_FLAG ) { 3307restart_edit = 'R' ; 3308 }else { 3309restart_edit = 'I' ; 3310 } 3311if (virtual_active (curwin )) { 3312ins_at_eol = false;// cursor always keeps its column 3313 }else { 3314ins_at_eol = (gchar_cursor ()== NUL ); 3315 } 3316} 3317 3318// If the cursor is on an indent, ^T/^D insert/delete one 3319// shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>". 3320// Always round the indent to 'shiftwidth', this is compatible 3321// with vi. But vi only supports ^T and ^D after an 3322// autoindent, we support it everywhere. 3323static void ins_shift (int c ,int lastc ) 3324{ 3325if (stop_arrow ()== FAIL ) { 3326return ; 3327 } 3328redo_append_char (c ); 3329 3330// 0^D and ^^D: remove all indent. 3331if (c == Ctrl_D && (lastc == '0' || lastc == '^' ) 3332&& curwin -> w_cursor .col > 0 ) { 3333curwin -> w_cursor .col -- ; 3334del_char (false);// delete the '^' or '0' 3335// In Replace mode, restore the characters that '^' or '0' replaced. 3336if (State & REPLACE_FLAG ) { 3337replace_pop_ins (); 3338 } 3339if (lastc == '^' ) { 3340old_indent = get_indent ();// remember curr. indent 3341 } 3342change_indent (INDENT_SET ,0 , true, true); 3343 }else { 3344change_indent (c == Ctrl_D ?INDENT_DEC :INDENT_INC ,0 , true, true); 3345 } 3346 3347if (Ins .did_ai && * skipwhite (get_cursor_line_ptr ())!= NUL ) { 3348Ins .did_ai = false; 3349 } 3350Ins .did_si = false; 3351Ins .can_si = false; 3352Ins .can_si_back = false; 3353Ins .can_cindent = false;// no cindenting after ^D or ^T 3354} 3355 3356static void ins_del (void ) 3357{ 3358if (stop_arrow ()== FAIL ) { 3359return ; 3360 } 3361if (gchar_cursor ()== NUL ) {// delete newline 3362const int temp = curwin -> w_cursor .col ; 3363if (!can_bs (BS_EOL )// only if "eol" included 3364|| do_join (2 , false, true, false, false)== FAIL ) { 3365vim_beep (kOptBoFlagBackspace ); 3366 }else { 3367mc_ins_join (); 3368curwin -> w_cursor .col = temp ; 3369// Adjust orig_line_count in case more lines have been deleted than 3370// have been added. That makes sure, that open_line() later 3371// can access all buffer lines correctly 3372if (State & VREPLACE_FLAG 3373&& orig_line_count > curbuf -> b_ml .ml_line_count ) { 3374orig_line_count = curbuf -> b_ml .ml_line_count ; 3375 } 3376 } 3377 }else if (del_char (false)== FAIL ) {// delete char under cursor 3378vim_beep (kOptBoFlagBackspace ); 3379 } 3380Ins .did_ai = false; 3381Ins .did_si = false; 3382Ins .can_si = false; 3383Ins .can_si_back = false; 3384redo_append_char (K_DEL ); 3385} 3386 3387/// Handle Backspace, delete-word and delete-line in Insert mode. 3388/// 3389/// @param c character that was typed 3390/// @param mode backspace mode to use 3391/// @param[in,out] inserted_space_p whether a space was the last 3392// character inserted 3393/// 3394/// @return true when backspace was actually used. 3395static bool ins_bs (int c ,int mode ,int * inserted_space_p ) 3396FUNC_ATTR_NONNULL_ARG (3 ) 3397{ 3398int cc ; 3399int temp = 0 ;// init for GCC 3400bool did_backspace = false; 3401bool call_fix_indent = false; 3402 3403// can't delete anything in an empty file 3404// can't backup past first character in buffer 3405// can't backup past starting point unless 'backspace' > 1 3406// can backup to a previous line if 'backspace' == 0 3407if (buf_is_empty (curbuf ) 3408|| (!Ins .revins_on 3409&& ((curwin -> w_cursor .lnum == 1 && curwin -> w_cursor .col == 0 ) 3410|| (!can_bs (BS_START ) 3411&& ((Ins .moved != kInsNone && !bt_prompt (curbuf )) 3412|| (curwin -> w_cursor .lnum == Ins .start_orig .lnum 3413&& curwin -> w_cursor .col <=Ins .start_orig .col ))) 3414|| (!can_bs (BS_INDENT )&& Ins .moved == kInsNone && Ins .ai_col > 0 3415&& curwin -> w_cursor .col <=Ins .ai_col ) 3416|| (!can_bs (BS_EOL )&& curwin -> w_cursor .col == 0 )))) { 3417vim_beep (kOptBoFlagBackspace ); 3418return false; 3419 } 3420 3421if (stop_arrow ()== FAIL ) { 3422return false; 3423 } 3424bool in_indent = inindent (0 ); 3425if (in_indent ) { 3426Ins .can_cindent = false; 3427 } 3428Ins .end_comment_pending = NUL ;// After BS, don't auto-end comment 3429if (Ins .revins_on ) {// put cursor after last inserted char 3430inc_cursor (); 3431 } 3432// Virtualedit: 3433// BACKSPACE_CHAR eats a virtual space 3434// BACKSPACE_WORD eats all coladd 3435// BACKSPACE_LINE eats all coladd and keeps going 3436if (curwin -> w_cursor .coladd > 0 ) { 3437if (mode == BACKSPACE_CHAR ) { 3438curwin -> w_cursor .coladd -- ; 3439return true; 3440 } 3441if (mode == BACKSPACE_WORD ) { 3442curwin -> w_cursor .coladd = 0 ; 3443return true; 3444 } 3445curwin -> w_cursor .coladd = 0 ; 3446 } 3447 3448// Delete newline! 3449if (curwin -> w_cursor .col == 0 ) { 3450mc_ins_join (); 3451linenr_T lnum = Ins .start .lnum ; 3452if (curwin -> w_cursor .lnum == lnum || Ins .revins_on ) { 3453if (u_save ((linenr_T )(curwin -> w_cursor .lnum - 2 ), 3454 (linenr_T )(curwin -> w_cursor .lnum + 1 ))== FAIL ) { 3455return false; 3456 } 3457Ins .start .lnum -- ; 3458Ins .start .col = ml_get_len (Ins .start .lnum ); 3459 } 3460// In replace mode: 3461// cc < 0: NL was inserted, delete it 3462// cc >= 0: NL was replaced, put original characters back 3463cc = -1 ; 3464if (State & REPLACE_FLAG ) { 3465cc = replace_pop_if_nul ();// returns -1 if NL was inserted 3466 } 3467// In replace mode, in the line we started replacing, we only move the 3468// cursor. 3469if ((State & REPLACE_FLAG )&& curwin -> w_cursor .lnum <=lnum ) { 3470dec_cursor (); 3471 }else { 3472if (!(State & VREPLACE_FLAG ) 3473|| curwin -> w_cursor .lnum > orig_line_count ) { 3474temp = gchar_cursor ();// remember current char 3475curwin -> w_cursor .lnum -- ; 3476 3477// When "aw" is in 'formatoptions' we must delete the space at 3478// the end of the line, otherwise the line will be broken 3479// again when auto-formatting. 3480if (has_format_option (kFoAuto ) 3481&& has_format_option (kFoWhitePar )) { 3482const char * ptr = ml_get_buf (curbuf ,curwin -> w_cursor .lnum ); 3483int len = get_cursor_line_len (); 3484if (len > 0 && ptr [len - 1 ]== ' ' ) { 3485char * newp = xmemdupz (ptr , (size_t )(len - 1 )); 3486 3487if (curbuf -> b_ml .ml_flags & (ML_LINE_DIRTY |ML_ALLOCATED )) { 3488xfree (curbuf -> b_ml .ml_line_ptr ); 3489 } 3490curbuf -> b_ml .ml_line_ptr = newp ; 3491curbuf -> b_ml .ml_line_textlen -- ; 3492curbuf -> b_ml .ml_flags |=ML_LINE_DIRTY ; 3493 } 3494 } 3495 3496do_join (2 , false, false, false, false); 3497if (temp == NUL && gchar_cursor ()!= NUL ) { 3498inc_cursor (); 3499 } 3500 }else { 3501dec_cursor (); 3502 } 3503 3504// In MODE_REPLACE mode we have to put back the text that was 3505// replaced by the NL. On the replace stack is first a 3506// NUL-terminated sequence of characters that were deleted and then 3507// the characters that NL replaced. 3508if (State & REPLACE_FLAG ) { 3509// Do the next ins_char() in MODE_NORMAL state, to 3510// prevent ins_char() from replacing characters and 3511// avoiding showmatch(). 3512int oldState = State ; 3513State = MODE_NORMAL ; 3514// restore characters (blanks) deleted after cursor 3515while (cc > 0 ) { 3516colnr_T save_col = curwin -> w_cursor .col ; 3517mb_replace_pop_ins (); 3518curwin -> w_cursor .col = save_col ; 3519cc = replace_pop_if_nul (); 3520 } 3521// restore the characters that NL replaced 3522replace_pop_ins (); 3523State = oldState ; 3524 } 3525 } 3526Ins .did_ai = false; 3527 }else { 3528// Delete character(s) before the cursor. 3529if (Ins .revins_on ) {// put cursor on last inserted char 3530dec_cursor (); 3531 } 3532colnr_T mincol = 0 ; 3533// keep indent 3534if (mode == BACKSPACE_LINE 3535&& (curbuf -> b_p_ai || cindent_on ()) 3536&& !Ins .revins_on ) { 3537colnr_T save_col = curwin -> w_cursor .col ; 3538beginline (BL_WHITE ); 3539if (curwin -> w_cursor .col < save_col ) { 3540mincol = curwin -> w_cursor .col ; 3541// should now fix the indent to match with the previous line 3542call_fix_indent = true; 3543 } 3544curwin -> w_cursor .col = save_col ; 3545 } 3546 3547// Handle deleting one 'shiftwidth' or 'softtabstop'. 3548if (mode == BACKSPACE_CHAR 3549&& ((p_sta && in_indent ) 3550|| ((get_sts_value ()!= 0 || tabstop_count (curbuf -> b_p_vsts_array )) 3551&& curwin -> w_cursor .col > 0 3552&& (* (get_cursor_pos_ptr ()- 1 )== TAB 3553|| (* (get_cursor_pos_ptr ()- 1 )== ' ' 3554&& (!* inserted_space_p || Ins .moved != kInsNone )))))) { 3555* inserted_space_p = false; 3556 3557bool const use_ts = !curwin -> w_p_list || curwin -> w_p_lcs_chars .tab1 ; 3558char * const line = get_cursor_line_ptr (); 3559char * const cursor_ptr = line + curwin -> w_cursor .col ; 3560 3561colnr_T vcol = 0 ; 3562colnr_T space_vcol = 0 ; 3563StrCharInfo sci = utf_ptr2StrCharInfo (line ); 3564StrCharInfo space_sci = sci ; 3565bool prev_space = false; 3566 3567// Compute virtual column of cursor position, and find the last 3568// whitespace before cursor that is preceded by non-whitespace. 3569// Use charsize_nowrap() so that virtual text and wrapping are ignored. 3570while (sci .ptr < cursor_ptr ) { 3571bool cur_space = ascii_iswhite (sci .chr .value ); 3572if (!prev_space && cur_space ) { 3573space_sci = sci ; 3574space_vcol = vcol ; 3575 } 3576ClusterInfo cli = utf_ClusterInfo (sci ); 3577vcol += charsize_nowrap (curbuf ,sci .ptr ,use_ts ,vcol ,sci .chr .value ,cli .cells ); 3578sci = cli .next ; 3579prev_space = cur_space ; 3580 } 3581 3582// Compute the virtual column where we want to be. 3583colnr_T want_vcol = vcol > 0 ?vcol - 1 :0 ; 3584if (p_sta && in_indent ) { 3585want_vcol -= want_vcol %get_sw_value (curbuf ); 3586 }else { 3587want_vcol = tabstop_start (want_vcol ,get_sts_value (),curbuf -> b_p_vsts_array ); 3588 } 3589 3590// Find the position to stop backspacing. 3591// Use charsize_nowrap() so that virtual text and wrapping are ignored. 3592while (true) { 3593ClusterInfo cli = utf_ClusterInfo (space_sci ); 3594int size = charsize_nowrap (curbuf ,space_sci .ptr ,use_ts ,space_vcol ,space_sci .chr .value , 3595cli .cells ); 3596if (space_vcol + size > want_vcol ) { 3597break ; 3598 } 3599space_vcol += size ; 3600space_sci = cli .next ; 3601 } 3602colnr_T const want_col = (int )(space_sci .ptr - line ); 3603 3604// Delete characters until we are at or before want_col. 3605while (curwin -> w_cursor .col > want_col ) { 3606dec_cursor (); 3607if (State & REPLACE_FLAG ) { 3608// Don't delete characters before the insert point when in Replace mode. 3609if (curwin -> w_cursor .lnum != Ins .start .lnum 3610|| curwin -> w_cursor .col >=Ins .start .col ) { 3611replace_do_bs (-1 ); 3612 } 3613 }else { 3614del_char (false); 3615 } 3616 } 3617 3618// Insert extra spaces until we are at want_vcol. 3619for (;space_vcol < want_vcol ;space_vcol ++ ) { 3620// Remember the first char we inserted. 3621if (curwin -> w_cursor .lnum == Ins .start_orig .lnum 3622&& curwin -> w_cursor .col < Ins .start_orig .col ) { 3623Ins .start_orig .col = curwin -> w_cursor .col ; 3624 } 3625 3626if (State & VREPLACE_FLAG ) { 3627ins_char (' ' ); 3628 }else { 3629ins_str (S_LEN (" " )); 3630if ((State & REPLACE_FLAG )) { 3631replace_push_nul (); 3632 } 3633 } 3634 } 3635 }else { 3636// Delete up to starting point, start of line or previous word. 3637 3638int cclass = mb_get_class (get_cursor_pos_ptr ()); 3639do { 3640if (!Ins .revins_on ) {// put cursor on char to be deleted 3641dec_cursor (); 3642 } 3643cc = gchar_cursor (); 3644// look multi-byte character class 3645int prev_cclass = cclass ; 3646cclass = mb_get_class (get_cursor_pos_ptr ()); 3647if (mode == BACKSPACE_WORD && !ascii_isspace (cc )) {// start of word? 3648mode = BACKSPACE_WORD_NOT_SPACE ; 3649temp = vim_iswordc (cc ); 3650 }else if (mode == BACKSPACE_WORD_NOT_SPACE 3651&& ((ascii_isspace (cc )|| vim_iswordc (cc )!= temp ) 3652|| prev_cclass != cclass )) {// end of word? 3653if (!Ins .revins_on ) { 3654inc_cursor (); 3655 }else if (State & REPLACE_FLAG ) { 3656dec_cursor (); 3657 } 3658break ; 3659 } 3660if (State & REPLACE_FLAG ) { 3661replace_do_bs (-1 ); 3662 }else { 3663bool has_composing = false; 3664if (p_deco ) { 3665char * p0 = get_cursor_pos_ptr (); 3666has_composing = utf_composinglike (p0 ,p0 + utf_ptr2len (p0 ),NULL ); 3667 } 3668del_char (false); 3669// If there are combining characters and 'delcombine' is set 3670// move the cursor back. Don't back up before the base character. 3671if (has_composing ) { 3672inc_cursor (); 3673 } 3674if (Ins .revins_chars ) { 3675Ins .revins_chars -- ; 3676Ins .revins_legal ++ ; 3677 } 3678if (Ins .revins_on && gchar_cursor ()== NUL ) { 3679break ; 3680 } 3681 } 3682// Just a single backspace?: 3683if (mode == BACKSPACE_CHAR ) { 3684break ; 3685 } 3686 }while (Ins .revins_on 3687|| (curwin -> w_cursor .col > mincol 3688&& (can_bs (BS_NOSTOP ) 3689|| (curwin -> w_cursor .lnum != Ins .start_orig .lnum 3690|| curwin -> w_cursor .col != Ins .start_orig .col )))); 3691 } 3692did_backspace = true; 3693 } 3694Ins .did_si = false; 3695Ins .can_si = false; 3696Ins .can_si_back = false; 3697if (curwin -> w_cursor .col <=1 ) { 3698Ins .did_ai = false; 3699 } 3700 3701if (call_fix_indent ) { 3702fix_indent (); 3703 } 3704 3705// It's a little strange to put backspaces into the redo 3706// buffer, but it makes auto-indent a lot easier to deal 3707// with. 3708redo_append_char (c ); 3709 3710// If deleted before the insertion point, adjust it 3711if (curwin -> w_cursor .lnum == Ins .start_orig .lnum 3712&& curwin -> w_cursor .col < Ins .start_orig .col ) { 3713Ins .start_orig .col = curwin -> w_cursor .col ; 3714 } 3715 3716// vi behaviour: the cursor moves backward but the character that 3717// was there remains visible 3718// Vim behaviour: the cursor moves backward and the character that 3719// was there is erased from the screen. 3720// We can emulate the vi behaviour by pretending there is a dollar 3721// displayed even when there isn't. 3722// --pkv Sun Jan 19 01:56:40 EST 2003 3723if (vim_strchr (p_cpo ,kCpoBackspace )!= NULL && dollar_vcol == -1 ) { 3724dollar_vcol = curwin -> w_virtcol ; 3725 } 3726 3727// When deleting a char the cursor line must never be in a closed fold. 3728// E.g., when 'foldmethod' is indent and deleting the first non-white 3729// char before a Tab. 3730if (did_backspace ) { 3731foldOpenCursor (); 3732 } 3733return did_backspace ; 3734} 3735 3736static void ins_left (void ) 3737{ 3738const bool end_change = Ins .dont_sync_undo == kFalse ;// end undoable change 3739 3740if ((fdo_flags & kOptFdoFlagHor )&& KeyTyped ) { 3741foldOpenCursor (); 3742 } 3743undisplay_dollar (); 3744pos_T tpos = curwin -> w_cursor ; 3745if (oneleft ()== OK ) { 3746start_arrow_with_change (& tpos ,end_change ,K_LEFT ); 3747// If exit reversed string, position is fixed 3748if (Ins .revins_scol != -1 && (int )curwin -> w_cursor .col >=Ins .revins_scol ) { 3749Ins .revins_legal ++ ; 3750 } 3751Ins .revins_chars ++ ; 3752 }else if (vim_strchr (p_ww ,'[' )!= NULL && curwin -> w_cursor .lnum > 1 ) { 3753// if 'whichwrap' set for cursor in insert mode may go to previous line. 3754// always break undo when moving upwards/downwards, else undo may break 3755start_arrow (& tpos , true,K_LEFT ); 3756curwin -> w_cursor .lnum -- ; 3757coladvance (curwin ,MAXCOL ); 3758curwin -> w_set_curswant = true;// so we stay at the end 3759 }else { 3760vim_beep (kOptBoFlagCursor ); 3761 } 3762Ins .dont_sync_undo = kFalse ; 3763} 3764 3765static void ins_home (int c ) 3766{ 3767if ((fdo_flags & kOptFdoFlagHor )&& KeyTyped ) { 3768foldOpenCursor (); 3769 } 3770undisplay_dollar (); 3771pos_T tpos = curwin -> w_cursor ; 3772if (c == K_C_HOME ) { 3773curwin -> w_cursor .lnum = 1 ; 3774 } 3775curwin -> w_cursor .col = 0 ; 3776curwin -> w_cursor .coladd = 0 ; 3777curwin -> w_curswant = 0 ; 3778start_arrow (& tpos , true,c == K_C_HOME ?NUL :K_HOME ); 3779} 3780 3781static void ins_end (int c ) 3782{ 3783if ((fdo_flags & kOptFdoFlagHor )&& KeyTyped ) { 3784foldOpenCursor (); 3785 } 3786undisplay_dollar (); 3787pos_T tpos = curwin -> w_cursor ; 3788if (c == K_C_END ) { 3789curwin -> w_cursor .lnum = curbuf -> b_ml .ml_line_count ; 3790 } 3791coladvance (curwin ,MAXCOL ); 3792curwin -> w_curswant = MAXCOL ; 3793 3794start_arrow (& tpos , true,c == K_C_END ?NUL :K_END ); 3795} 3796 3797static void ins_s_left (void ) 3798{ 3799const bool end_change = Ins .dont_sync_undo == kFalse ;// end undoable change 3800if ((fdo_flags & kOptFdoFlagHor )&& KeyTyped ) { 3801foldOpenCursor (); 3802 } 3803undisplay_dollar (); 3804if (curwin -> w_cursor .lnum > 1 || curwin -> w_cursor .col > 0 ) { 3805start_arrow_with_change (& curwin -> w_cursor ,end_change ,K_S_LEFT ); 3806bck_word (1 , false, false); 3807curwin -> w_set_curswant = true; 3808 }else { 3809vim_beep (kOptBoFlagCursor ); 3810 } 3811Ins .dont_sync_undo = kFalse ; 3812} 3813 3814/// @param end_change end undoable change 3815static void ins_right (void ) 3816{ 3817const bool end_change = Ins .dont_sync_undo == kFalse ;// end undoable change 3818if ((fdo_flags & kOptFdoFlagHor )&& KeyTyped ) { 3819foldOpenCursor (); 3820 } 3821undisplay_dollar (); 3822if (gchar_cursor ()!= NUL || virtual_active (curwin )) { 3823start_arrow_with_change (& curwin -> w_cursor ,end_change ,K_RIGHT ); 3824curwin -> w_set_curswant = true; 3825if (virtual_active (curwin )) { 3826oneright (); 3827 }else { 3828curwin -> w_cursor .col += utfc_ptr2len (get_cursor_pos_ptr ()); 3829 } 3830 3831Ins .revins_legal ++ ; 3832if (Ins .revins_chars ) { 3833Ins .revins_chars -- ; 3834 } 3835 }else if (vim_strchr (p_ww ,']' )!= NULL 3836&& curwin -> w_cursor .lnum < curbuf -> b_ml .ml_line_count ) { 3837// if 'whichwrap' set for cursor in insert mode, may move the 3838// cursor to the next line 3839start_arrow (& curwin -> w_cursor , true,K_RIGHT ); 3840curwin -> w_set_curswant = true; 3841curwin -> w_cursor .lnum ++ ; 3842curwin -> w_cursor .col = 0 ; 3843 }else { 3844vim_beep (kOptBoFlagCursor ); 3845 } 3846Ins .dont_sync_undo = kFalse ; 3847} 3848 3849static void ins_s_right (void ) 3850{ 3851const bool end_change = Ins .dont_sync_undo == kFalse ;// end undoable change 3852if ((fdo_flags & kOptFdoFlagHor )&& KeyTyped ) { 3853foldOpenCursor (); 3854 } 3855undisplay_dollar (); 3856if (curwin -> w_cursor .lnum < curbuf -> b_ml .ml_line_count 3857|| gchar_cursor ()!= NUL ) { 3858start_arrow_with_change (& curwin -> w_cursor ,end_change ,K_S_RIGHT ); 3859fwd_word (1 , false,0 ); 3860curwin -> w_set_curswant = true; 3861 }else { 3862vim_beep (kOptBoFlagCursor ); 3863 } 3864Ins .dont_sync_undo = kFalse ; 3865} 3866 3867/// @param startcol when true move to Ins.start.col 3868static void ins_up (bool startcol ) 3869{ 3870linenr_T old_topline = curwin -> w_topline ; 3871int old_topfill = curwin -> w_topfill ; 3872 3873undisplay_dollar (); 3874pos_T tpos = curwin -> w_cursor ; 3875if (cursor_up (1 , true)== OK ) { 3876if (startcol ) { 3877coladvance (curwin ,getvcol_nolist (& Ins .start )); 3878 } 3879if (old_topline != curwin -> w_topline 3880|| old_topfill != curwin -> w_topfill ) { 3881redraw_later (curwin ,UPD_VALID ); 3882 } 3883start_arrow (& tpos , true,startcol ?'k' :K_UP ); 3884Ins .can_cindent = true; 3885 }else { 3886vim_beep (kOptBoFlagCursor ); 3887 } 3888} 3889 3890static void ins_pageup (void ) 3891{ 3892undisplay_dollar (); 3893 3894if (mod_mask & MOD_MASK_CTRL ) { 3895// <C-PageUp>: tab page back 3896if (first_tabpage -> tp_next != NULL ) { 3897start_arrow (& curwin -> w_cursor , true,NUL ); 3898goto_tabpage (-1 ); 3899 } 3900return ; 3901 } 3902 3903pos_T tpos = curwin -> w_cursor ; 3904if (pagescroll (BACKWARD ,1 , false)== OK ) { 3905start_arrow (& tpos , true,NUL ); 3906Ins .can_cindent = true; 3907 }else { 3908vim_beep (kOptBoFlagCursor ); 3909 } 3910} 3911 3912/// @param startcol when true move to Ins.start.col 3913static void ins_down (bool startcol ) 3914{ 3915linenr_T old_topline = curwin -> w_topline ; 3916int old_topfill = curwin -> w_topfill ; 3917 3918undisplay_dollar (); 3919pos_T tpos = curwin -> w_cursor ; 3920if (cursor_down (1 , true)== OK ) { 3921if (startcol ) { 3922coladvance (curwin ,getvcol_nolist (& Ins .start )); 3923 } 3924if (old_topline != curwin -> w_topline 3925|| old_topfill != curwin -> w_topfill ) { 3926redraw_later (curwin ,UPD_VALID ); 3927 } 3928start_arrow (& tpos , true,startcol ?'j' :K_DOWN ); 3929Ins .can_cindent = true; 3930 }else { 3931vim_beep (kOptBoFlagCursor ); 3932 } 3933} 3934 3935static void ins_pagedown (void ) 3936{ 3937undisplay_dollar (); 3938 3939if (mod_mask & MOD_MASK_CTRL ) { 3940// <C-PageDown>: tab page forward 3941if (first_tabpage -> tp_next != NULL ) { 3942start_arrow (& curwin -> w_cursor , true,NUL ); 3943goto_tabpage (0 ); 3944 } 3945return ; 3946 } 3947 3948pos_T tpos = curwin -> w_cursor ; 3949if (pagescroll (FORWARD ,1 , false)== OK ) { 3950start_arrow (& tpos , true,NUL ); 3951Ins .can_cindent = true; 3952 }else { 3953vim_beep (kOptBoFlagCursor ); 3954 } 3955} 3956 3957/// Handle TAB in Insert or Replace mode. 3958/// 3959/// @return true when the TAB needs to be inserted like a normal character. 3960static bool ins_tab (void ) 3961FUNC_ATTR_WARN_UNUSED_RESULT 3962{ 3963int temp ; 3964 3965if (Ins .start_blank_vcol == MAXCOL && curwin -> w_cursor .lnum == Ins .start .lnum ) { 3966Ins .start_blank_vcol = get_nolist_virtcol (); 3967 } 3968if (echeck_abbr (TAB + ABBR_OFF )) { 3969return false; 3970 } 3971 3972bool ind = inindent (0 ); 3973if (ind ) { 3974Ins .can_cindent = false; 3975 } 3976 3977// When nothing special, insert TAB like a normal character. 3978if (!curbuf -> b_p_et 3979&& !( 3980p_sta 3981&& ind 3982// These five lines mean 'tabstop' != 'shiftwidth' 3983&& ((tabstop_count (curbuf -> b_p_vts_array )> 1 ) 3984|| (tabstop_count (curbuf -> b_p_vts_array )== 1 3985&& tabstop_first (curbuf -> b_p_vts_array ) 3986!= get_sw_value (curbuf )) 3987|| (tabstop_count (curbuf -> b_p_vts_array )== 0 3988&& curbuf -> b_p_ts != get_sw_value (curbuf )))) 3989&& tabstop_count (curbuf -> b_p_vsts_array )== 0 && get_sts_value ()== 0 ) { 3990return true; 3991 } 3992 3993if (stop_arrow ()== FAIL ) { 3994return true; 3995 } 3996 3997Ins .did_ai = false; 3998Ins .did_si = false; 3999Ins .can_si = false; 4000Ins .can_si_back = false; 4001redo_append_str (S_LEN ("\t" )); 4002 4003if (p_sta && ind ) {// insert tab in indent, use 'shiftwidth' 4004temp = get_sw_value (curbuf ); 4005temp -= get_nolist_virtcol () %temp ; 4006 }else if (tabstop_count (curbuf -> b_p_vsts_array )> 0 4007|| curbuf -> b_p_sts != 0 ) { 4008// use 'softtabstop' when set 4009temp = tabstop_padding (get_nolist_virtcol (), 4010get_sts_value (), 4011curbuf -> b_p_vsts_array ); 4012 }else { 4013// otherwise use 'tabstop' 4014temp = tabstop_padding (get_nolist_virtcol (), 4015curbuf -> b_p_ts , 4016curbuf -> b_p_vts_array ); 4017 } 4018 4019// Insert the first space with ins_char(). It will delete one char in 4020// replace mode. Insert the rest with ins_str(); it will not delete any 4021// chars. For MODE_VREPLACE state, we use ins_char() for all characters. 4022ins_char (' ' ); 4023while (-- temp > 0 ) { 4024if (State & VREPLACE_FLAG ) { 4025ins_char (' ' ); 4026 }else { 4027ins_str (S_LEN (" " )); 4028if (State & REPLACE_FLAG ) {// no char replaced 4029replace_push_nul (); 4030 } 4031 } 4032 } 4033 4034// When 'expandtab' not set: Replace spaces by TABs where possible. 4035if (!curbuf -> b_p_et && (tabstop_count (curbuf -> b_p_vsts_array )> 0 4036|| get_sts_value ()> 0 4037|| (p_sta && ind ))) { 4038char * ptr ; 4039char * saved_line = NULL ;// init for GCC 4040pos_T pos ; 4041pos_T * cursor ; 4042colnr_T want_vcol ,vcol ; 4043int change_col = -1 ; 4044int save_list = curwin -> w_p_list ; 4045 4046// Get the current line. For MODE_VREPLACE state, don't make real 4047// changes yet, just work on a copy of the line. 4048if (State & VREPLACE_FLAG ) { 4049pos = curwin -> w_cursor ; 4050cursor = & pos ; 4051saved_line = xstrnsave (get_cursor_line_ptr (), (size_t )get_cursor_line_len ()); 4052ptr = saved_line + pos .col ; 4053 }else { 4054ptr = get_cursor_pos_ptr (); 4055cursor = & curwin -> w_cursor ; 4056 } 4057 4058// When 'L' is not in 'cpoptions' a tab always takes up 'ts' spaces. 4059if (vim_strchr (p_cpo ,kCpoListwm )== NULL ) { 4060curwin -> w_p_list = false; 4061 } 4062 4063// Find first white before the cursor 4064pos_T fpos = curwin -> w_cursor ; 4065while (fpos .col > 0 && ascii_iswhite (ptr [-1 ])) { 4066fpos .col -- ; 4067ptr -- ; 4068 } 4069 4070// In Replace mode, don't change characters before the insert point. 4071if ((State & REPLACE_FLAG ) 4072&& fpos .lnum == Ins .start .lnum 4073&& fpos .col < Ins .start .col ) { 4074ptr += Ins .start .col - fpos .col ; 4075fpos .col = Ins .start .col ; 4076 } 4077 4078// compute virtual column numbers of first white and cursor 4079getvcol (curwin ,& fpos ,& vcol ,NULL ,NULL ,0 ); 4080getvcol (curwin ,cursor ,& want_vcol ,NULL ,NULL ,0 ); 4081 4082char * tab = "\t" ; 4083int32_t tab_v = (uint8_t )(* tab ); 4084 4085CharsizeArg csarg ; 4086CSType cstype = init_charsize_arg (& csarg ,curwin ,0 ,tab ); 4087 4088// Use as many TABs as possible. Beware of 'breakindent', 'showbreak' 4089// and 'linebreak' adding extra virtual columns. 4090while (ascii_iswhite (* ptr )) { 4091int i = win_charsize (cstype ,vcol ,tab ,tab_v ,& csarg ,1 ).width ; 4092if (vcol + i > want_vcol ) { 4093break ; 4094 } 4095if (* ptr != TAB ) { 4096* ptr = TAB ; 4097if (change_col < 0 ) { 4098change_col = fpos .col ;// Column of first change 4099// May have to adjust Ins.start 4100if (fpos .lnum == Ins .start .lnum && fpos .col < Ins .start .col ) { 4101Ins .start .col = fpos .col ; 4102 } 4103 } 4104 } 4105fpos .col ++ ; 4106ptr ++ ; 4107vcol += i ; 4108 } 4109 4110if (change_col >=0 ) { 4111int repl_off = 0 ; 4112// Skip over the spaces we need. 4113cstype = init_charsize_arg (& csarg ,curwin ,0 ,ptr ); 4114while (vcol < want_vcol && * ptr == ' ' ) { 4115vcol += win_charsize (cstype ,vcol ,ptr ,' ' ,& csarg ,1 ).width ; 4116ptr ++ ; 4117repl_off ++ ; 4118 } 4119 4120if (vcol > want_vcol ) { 4121// Must have a char with 'showbreak' just before it. 4122ptr -- ; 4123repl_off -- ; 4124 } 4125fpos .col += repl_off ; 4126 4127// Delete following spaces. 4128int i = cursor -> col - fpos .col ; 4129if (i > 0 ) { 4130if (!(State & VREPLACE_FLAG )) { 4131const colnr_T newp_len = curbuf -> b_ml .ml_line_textlen - i ; 4132char * newp = xmalloc ((size_t )newp_len ); 4133ptrdiff_t col = ptr - curbuf -> b_ml .ml_line_ptr ; 4134if (col > 0 ) { 4135memmove (newp ,ptr - col , (size_t )col ); 4136 } 4137memmove (newp + col ,ptr + i , (size_t )(newp_len - col )); 4138if (curbuf -> b_ml .ml_flags & (ML_LINE_DIRTY |ML_ALLOCATED )) { 4139xfree (curbuf -> b_ml .ml_line_ptr ); 4140 } 4141curbuf -> b_ml .ml_line_ptr = newp ; 4142curbuf -> b_ml .ml_line_textlen = newp_len ; 4143curbuf -> b_ml .ml_flags = (curbuf -> b_ml .ml_flags |ML_LINE_DIRTY )& ~ML_EMPTY ; 4144inserted_bytes (fpos .lnum ,change_col , 4145cursor -> col - change_col ,fpos .col - change_col ); 4146 }else { 4147STRMOVE (ptr ,ptr + i ); 4148 } 4149// correct replace stack. 4150if ((State & REPLACE_FLAG )&& !(State & VREPLACE_FLAG )) { 4151for (temp = i ;-- temp >=0 ;) { 4152replace_join (repl_off ); 4153 } 4154 } 4155 } 4156cursor -> col -= i ; 4157 4158// In MODE_VREPLACE state, we haven't changed anything yet. Do it 4159// now by backspacing over the changed spacing and then inserting 4160// the new spacing. 4161if (State & VREPLACE_FLAG ) { 4162// Backspace from real cursor to change_col 4163backspace_until_column (change_col ); 4164 4165// Insert each char in saved_line from changed_col to 4166// ptr-cursor 4167ins_bytes_len (saved_line + change_col , (size_t )(cursor -> col - change_col )); 4168 } 4169 } 4170 4171if (State & VREPLACE_FLAG ) { 4172xfree (saved_line ); 4173 } 4174curwin -> w_p_list = save_list ; 4175 } 4176 4177return false; 4178} 4179 4180/// Handle CR or NL in insert mode. 4181/// 4182/// @return false when it can't undo. 4183bool ins_eol (int c ) 4184{ 4185if (echeck_abbr (c + ABBR_OFF )) { 4186return true; 4187 } 4188if (stop_arrow ()== FAIL ) { 4189return false; 4190 } 4191undisplay_dollar (); 4192 4193// Strange Vi behaviour: In Replace mode, typing a NL will not delete the 4194// character under the cursor. Only push a NUL on the replace stack, 4195// nothing to put back when the NL is deleted. 4196if ((State & REPLACE_FLAG )&& !(State & VREPLACE_FLAG )) { 4197replace_push_nul (); 4198 } 4199 4200// In MODE_VREPLACE state, a NL replaces the rest of the line, and starts 4201// replacing the next line, so we push all of the characters left on the 4202// line onto the replace stack. This is not done here though, it is done 4203// in open_line(). 4204 4205// Put cursor on NUL if on the last char and coladd is 1 (happens after 4206// CTRL-O). 4207if (virtual_active (curwin )&& curwin -> w_cursor .coladd > 0 ) { 4208coladvance (curwin ,getviscol ()); 4209 } 4210 4211// NL in reverse insert will always start in the end of current line. 4212if (Ins .revins_on ) { 4213curwin -> w_cursor .col += get_cursor_pos_len (); 4214 } 4215 4216redo_append_str (S_LEN (NL_STR )); 4217bool i = open_line (FORWARD , 4218has_format_option (kFoRetComs ) ?OPENLINE_DO_COM :0 , 4219old_indent ,NULL ); 4220old_indent = 0 ; 4221Ins .can_cindent = true; 4222// When inserting a line the cursor line must never be in a closed fold. 4223foldOpenCursor (); 4224 4225return i ; 4226} 4227 4228// Handle digraph in insert mode. 4229// Returns character still to be inserted, or NUL when nothing remaining to be 4230// done. 4231static int ins_digraph (void ) 4232{ 4233bool did_putchar = false; 4234 4235pc_status = PC_STATUS_UNSET ; 4236if (redrawing ()&& !char_avail ()) { 4237// may need to redraw when no more chars available now 4238ins_redraw (false); 4239 4240edit_putchar ('?' , true); 4241did_putchar = true; 4242add_to_showcmd_c (Ctrl_K ); 4243 } 4244 4245// don't map the digraph chars. This also prevents the 4246// mode message to be deleted when ESC is hit 4247no_mapping ++ ; 4248allow_keys ++ ; 4249int c = plain_vgetc (); 4250no_mapping -- ; 4251allow_keys -- ; 4252if (did_putchar ) { 4253// when the line fits in 'columns' the '?' is at the start of the next 4254// line and will not be removed by the redraw 4255edit_unputchar (); 4256 } 4257 4258if (IS_SPECIAL (c )|| mod_mask ) {// special key 4259clear_showcmd (); 4260insert_special (c , true, false); 4261return NUL ; 4262 } 4263if (c != ESC ) { 4264did_putchar = false; 4265if (redrawing ()&& !char_avail ()) { 4266// may need to redraw when no more chars available now 4267ins_redraw (false); 4268 4269if (char2cells (c )== 1 ) { 4270ins_redraw (false); 4271edit_putchar (c , true); 4272did_putchar = true; 4273 } 4274add_to_showcmd_c (c ); 4275 } 4276no_mapping ++ ; 4277allow_keys ++ ; 4278int cc = plain_vgetc (); 4279no_mapping -- ; 4280allow_keys -- ; 4281if (did_putchar ) { 4282// when the line fits in 'columns' the '?' is at the start of the 4283// next line and will not be removed by a redraw 4284edit_unputchar (); 4285 } 4286if (cc != ESC ) { 4287redo_append_str (S_LEN (CTRL_V_STR )); 4288c = digraph_get (c ,cc , true); 4289clear_showcmd (); 4290return c ; 4291 } 4292 } 4293clear_showcmd (); 4294return NUL ; 4295} 4296 4297// Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line. 4298// Returns the char to be inserted, or NUL if none found. 4299int ins_copychar (linenr_T lnum ) 4300{ 4301if (lnum < 1 || lnum > curbuf -> b_ml .ml_line_count ) { 4302vim_beep (kOptBoFlagCopy ); 4303return NUL ; 4304 } 4305 4306// try to advance to the cursor column 4307validate_virtcol (curwin ); 4308int const end_vcol = curwin -> w_virtcol ; 4309char * line = ml_get (lnum ); 4310 4311CharsizeArg csarg ; 4312CSType cstype = init_charsize_arg (& csarg ,curwin ,lnum ,line ); 4313StrCharInfo ci = utf_ptr2StrCharInfo (line ); 4314int vcol = 0 ; 4315while (vcol < end_vcol && * ci .ptr != NUL ) { 4316ClusterInfo cli = utf_ClusterInfo (ci ); 4317vcol += win_charsize (cstype ,vcol ,ci .ptr ,ci .chr .value ,& csarg ,cli .cells ).width ; 4318if (vcol > end_vcol ) { 4319break ; 4320 } 4321ci = cli .next ; 4322 } 4323 4324int c = ci .chr .value < 0 ? (uint8_t )(* ci .ptr ) :ci .chr .value ; 4325if (c == NUL ) { 4326vim_beep (kOptBoFlagCopy ); 4327 } 4328return c ; 4329} 4330 4331// CTRL-Y or CTRL-E typed in Insert mode. 4332static int ins_ctrl_ey (int tc ) 4333{ 4334int c = tc ; 4335 4336if (ctrl_x_mode_scroll ()) { 4337if (c == Ctrl_Y ) { 4338scrolldown_clamp (); 4339 }else { 4340scrollup_clamp (); 4341 } 4342redraw_later (curwin ,UPD_VALID ); 4343 }else { 4344c = ins_copychar (curwin -> w_cursor .lnum + (c == Ctrl_Y ?-1 :1 )); 4345if (c != NUL ) { 4346// The character must be taken literally, insert like it 4347// was typed after a CTRL-V, and pretend 'textwidth' 4348// wasn't set. Digits, 'o' and 'x' are special after a 4349// CTRL-V, don't use it for these. 4350if (c < 256 && !isalnum (c )) { 4351redo_append_str (S_LEN (CTRL_V_STR )); 4352 } 4353OptInt tw_save = curbuf -> b_p_tw ; 4354curbuf -> b_p_tw = -1 ; 4355insert_special (c , true, false); 4356curbuf -> b_p_tw = tw_save ; 4357Ins .revins_chars ++ ; 4358Ins .revins_legal ++ ; 4359c = Ctrl_V ;// pretend CTRL-V is last character 4360auto_format (false, true); 4361 } 4362 } 4363return c ; 4364} 4365 4366// Get the value that w_virtcol would have when 'list' is off. 4367// Unless 'cpo' contains the 'L' flag. 4368colnr_T get_nolist_virtcol (void ) 4369{ 4370// check validity of cursor in current buffer 4371if (curwin -> w_buffer == NULL || curwin -> w_buffer -> b_ml .ml_mfp == NULL 4372|| curwin -> w_cursor .lnum > curwin -> w_buffer -> b_ml .ml_line_count ) { 4373return 0 ; 4374 } 4375if (curwin -> w_p_list && vim_strchr (p_cpo ,kCpoListwm )== NULL ) { 4376return getvcol_nolist (& curwin -> w_cursor ); 4377 } 4378validate_virtcol (curwin ); 4379return curwin -> w_virtcol ; 4380} 4381 4382// Handle the InsertCharPre autocommand. 4383// "c" is the character that was typed. 4384// Return a pointer to allocated memory with the replacement string. 4385// Return NULL to continue inserting "c". 4386static char * do_insert_char_pre (int c ) 4387{ 4388char buf [MB_MAXBYTES + 1 ]; 4389const int save_State = State ; 4390 4391if (c == Ctrl_RSB // i_CTRL-] only triggers abbreviations. 4392// Stuffed text was transformed when typed and appended to redobuf (redo_append_lit). 4393// Like abbreviations (vgetorpeek()), don't transform it again. 4394|| KeyStuffed 4395|| !has_event (EVENT_INSERTCHARPRE )) { 4396return NULL ; 4397 } 4398 4399size_t buflen = (size_t )utf_char2bytes (c ,buf ); 4400buf [buflen ]= NUL ; 4401 4402// Lock the text to avoid weird things from happening. 4403textlock ++ ; 4404set_vim_var_string (VV_CHAR ,buf , (ptrdiff_t )buflen );// set v:char 4405 4406char * res = NULL ; 4407if (ins_apply_autocmds (EVENT_INSERTCHARPRE )) { 4408// Get the value of v:char. It may be empty or more than one 4409// character. Only use it when changed, otherwise continue with the 4410// original character to avoid breaking autoindent. 4411if (strcmp (buf ,get_vim_var_str (VV_CHAR ))!= 0 ) { 4412res = xstrdup (get_vim_var_str (VV_CHAR )); 4413 } 4414 } 4415 4416set_vim_var_string (VV_CHAR ,NULL ,-1 ); 4417textlock -- ; 4418 4419// Restore the State, it may have been changed. 4420State = save_State ; 4421 4422return res ; 4423} 4424 4425bool get_can_cindent (void ) 4426{ 4427return Ins .can_cindent ; 4428} 4429 4430void set_can_cindent (bool val ) 4431{ 4432Ins .can_cindent = val ; 4433} 4434 4435/// Trigger "event" and take care of fixing undo. 4436int ins_apply_autocmds (event_T event ) 4437{ 4438varnumber_T tick = buf_get_changedtick (curbuf ); 4439 4440int r = apply_autocmds (event ,NULL ,NULL , false,curbuf ); 4441 4442// If u_savesub() was called then we are not prepared to start 4443// a new line. Call u_save() with no contents to fix that. 4444// Except when leaving Insert mode. 4445if (event != EVENT_INSERTLEAVE && tick != buf_get_changedtick (curbuf )) { 4446u_save (curwin -> w_cursor .lnum , (linenr_T )(curwin -> w_cursor .lnum + 1 )); 4447 } 4448 4449return r ; 4450}