robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// input.c: The input engine "bytes layer" (input_cmdatom.c is the "policy layer"). 2// 3// - Get a character from the user, a script file, or the keybufs described below. 4// - Apply mappings and abbreviations to typed keys (the :map tables live in mapping.c; the 5// matching loop is handle_mapping()). 6// - Assemble K_SPECIAL/multibyte byte sequences into keys (vgetc()). 7// - Record macros (recordbuff); capture the redo state (redobuff: "." capture and replay). 8// 9// Concepts: 10// - "Stuffing" = when some internal logic pushes keys to execute next. This is how a cmd 11// "translates" into another cmd: "x" stuffs "dl", "." stuffs the redo buf. 12// - XXX NOTE: stuffed keys must have a consumer in the current codepath (not "later on the main 13// loop"). There are 3 different rituals, depending on the consumer: 14// 1. basic translation: stuff, then exec_stuffed(); runs as CmdFrames of the stuffing command. 15// 2. input staged for a nested reader (getcmdline(), edit()): stuff only. 16// 3. main-loop wakeup (K_NOP): stuffed so it precedes input (unlike an event). 17// - TYPEAHEAD vs READ-AHEAD: 18// - typeahead = external input that arrived faster than can be executed (user typed fast). 19// - readahead = Nvim's own self-input. 20// - vgetorpeek() drains it BEFORE typeahead. 21// - Its keys are never mapped (mappings apply only to the 22// typebuf; abbreviations are disabled too), though they count as typed for most purposes 23// (KeyStuffed). 24// 25// These buffers are used: 26// 27// input ──► [ typebuf │ readbuf2 (redo) │ readbuf1 (stuff) ] ──► vgetc() ──► exec 28// ▲ mappings expand at typebuf front 29// 30// - typeahead (`typebuf`). 31// - readahead/stuff buffers (`readbuf1`, `readbuf2`). 32// - Two stuff buffers, because stuffing nests: a cmd executed FROM redo keys (readbuf2) may 33// itself stuff a translation (readbuf1), which must be consumed before the remaining redo. 34// - `redobuff` (RedoState): the current + previous change. 35// - `recordbuff`: accumulates the keys of a recording ("q"). 36// 37// Buffer bytes use "typeahead encoding": 38// - K_SPECIAL introduces a special key (two more bytes follow). 39// A literal K_SPECIAL is stored as K_SPECIAL KS_SPECIAL KE_FILLER. 40// - These translations are also done on multi-byte characters! 41// - Escaping K_SPECIAL is done by inchar(). 42// - Un-escaping is done by vgetc(). 43 44#include <assert.h> 45#include <limits.h> 46#include <stdbool.h> 47#include <stddef.h> 48#include <stdint.h> 49#include <stdio.h> 50#include <stdlib.h> 51#include <string.h> 52 53#include "klib/kvec.h" 54#include "nvim/api/private/defs.h" 55#include "nvim/api/private/helpers.h" 56#include "nvim/api/vim.h" 57#include "nvim/ascii_defs.h" 58#include "nvim/buffer_defs.h" 59#include "nvim/charset.h" 60#include "nvim/cursor.h" 61#include "nvim/drawscreen.h" 62#include "nvim/errors.h" 63#include "nvim/eval.h" 64#include "nvim/eval/typval.h" 65#include "nvim/eval/typval_defs.h" 66#include "nvim/eval/vars.h" 67#include "nvim/event/loop.h" 68#include "nvim/event/multiqueue.h" 69#include "nvim/ex_cmds.h" 70#include "nvim/ex_docmd.h" 71#include "nvim/ex_getln.h" 72#include "nvim/ex_getln_defs.h" 73#include "nvim/garray.h" 74#include "nvim/garray_defs.h" 75#include "nvim/gettext_defs.h" 76#include "nvim/globals.h" 77#include "nvim/input.h" 78#include "nvim/input_cmdatom.h" 79#include "nvim/insert.h" 80#include "nvim/insexpand.h" 81#include "nvim/keycodes.h" 82#include "nvim/lua/executor.h" 83#include "nvim/macros_defs.h" 84#include "nvim/main.h" 85#include "nvim/mapping.h" 86#include "nvim/mapping_defs.h" 87#include "nvim/mbyte.h" 88#include "nvim/mbyte_defs.h" 89#include "nvim/mcursor.h" 90#include "nvim/memline.h" 91#include "nvim/memory.h" 92#include "nvim/memory_defs.h" 93#include "nvim/message.h" 94#include "nvim/mouse.h" 95#include "nvim/move.h" 96#include "nvim/normal.h" 97#include "nvim/normal_defs.h" 98#include "nvim/ops.h" 99#include "nvim/option_vars.h" 100#include "nvim/os/fileio.h" 101#include "nvim/os/fileio_defs.h" 102#include "nvim/os/input.h" 103#include "nvim/os/os.h" 104#include "nvim/os/os_defs.h" 105#include "nvim/plines.h" 106#include "nvim/pos_defs.h" 107#include "nvim/register.h" 108#include "nvim/state.h" 109#include "nvim/state_defs.h" 110#include "nvim/strings.h" 111#include "nvim/types_defs.h" 112#include "nvim/ui.h" 113#include "nvim/undo.h" 114#include "nvim/vim_defs.h" 115 116/// State for adding bytes to a recording or 'showcmd'. 117typedef struct { 118uint8_t buf [MB_MAXBYTES * 3 + 4 ]; 119int prev_c ; 120size_t buflen ; 121unsigned pending_special ; 122unsigned pending_mbyte ; 123}gotchars_state_T ; 124 125/// Index in scriptin 126static int curscript = -1 ; 127/// Streams to read script from 128static FileDescriptor scriptin [NSCRIPT ]= {0 }; 129 130/// The current + previous change. redo_append_xx() captures in `redobuff.cur`; "." replays it. 131static RedoState redobuff ; 132/// Macro recording. 133static StringBuilder recordbuff = KV_INITIAL_VALUE ; 134/// First readahead buffer ("stuffbuf"): command translations ("x" => "dl"). Drains before readbuf2. 135static StuffBuf readbuf1 ; 136/// Second readahead buffer ("stuffbuf"): "." replay (start_redo()). 137static StuffBuf readbuf2 ; 138static UngotKey ungot = { .c = -1 }; 139 140/// Buffer used to store typed characters for vim.on_key(). 141static kvec_withinit_t (char ,MAXMAPLEN + 1 )on_key_buf = KVI_INITIAL_VALUE (on_key_buf ); 142 143/// Number of following bytes that should not be stored for vim.on_key(). 144static size_t on_key_ignore_len = 0 ; 145/// Nesting depth of getchar()/getcharstr(). Will skip vim.on_key() callbacks. #40010 146static int getchar_depth = 0 ; 147 148static int typeahead_char = 0 ;///< typeahead char that's not flushed 149 150/// When block_redo is true the redo buffer will not be changed. 151/// Used by edit() to repeat insertions. 152static bool block_redo = false; 153 154static int KeyNoremap = 0 ;///< remapping flags 155 156/// Variables used by vgetorpeek() and flush_buffers() 157/// 158/// typebuf.tb_buf[] contains all characters that are not consumed yet. 159/// typebuf.tb_buf[typebuf.tb_off] is the first valid character. 160/// typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1] is the last valid char. 161/// typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len] must be NUL. 162/// The head of the buffer may contain the result of mappings, abbreviations 163/// and @a commands. The length of this part is typebuf.tb_maplen. 164/// typebuf.tb_silent is the part where <silent> applies. 165/// After the head are characters that come from the terminal. 166/// typebuf.tb_no_abbr_cnt is the number of characters in typebuf.tb_buf that 167/// should not be considered for abbreviations. 168/// Some parts of typebuf.tb_buf may not be mapped. These parts are remembered 169/// in typebuf.tb_noremap[], which is the same length as typebuf.tb_buf and 170/// contains RM_NONE for the characters that are not to be remapped. 171/// typebuf.tb_noremap[typebuf.tb_off] is the first valid flag. 172enum { 173RM_YES = 0 ,///< tb_noremap: remap 174RM_NONE = 1 ,///< tb_noremap: don't remap 175RM_SCRIPT = 2 ,///< tb_noremap: remap local script mappings 176RM_ABBR = 4 ,///< tb_noremap: don't remap, do abbrev. 177}; 178 179// typebuf.tb_buf has three parts: room in front (for result of mappings), the 180// middle for typeahead and room for new characters (which needs to be 3 * 181// MAXMAPLEN for the Amiga). 182#define TYPELEN_INIT (5 * (MAXMAPLEN + 3)) 183static uint8_t typebuf_init [TYPELEN_INIT ];///< initial typebuf.tb_buf 184static uint8_t noremapbuf_init [TYPELEN_INIT ];///< initial typebuf.tb_noremap 185 186static size_t last_recorded_len = 0 ;///< number of last recorded chars 187 188enum { 189KEYLEN_PART_KEY = -1 ,///< keylen value for incomplete key-code 190KEYLEN_PART_MAP = -2 ,///< keylen value for incomplete mapping 191}; 192 193#include "input.c.generated.h" 194 195static const char e_recursive_mapping []= N_ ("E223: Recursive mapping" ); 196static const char e_cmd_mapping_must_end_with_cr [] 197= N_ ("E1255: <Cmd> mapping must end with <CR>" ); 198static const char e_cmd_mapping_must_end_with_cr_before_second_cmd [] 199= N_ ("E1136: <Cmd> mapping must end with <CR> before second <Cmd>" ); 200static const char e_lua_mapping_gone []= N_ ("E5117: Lua mapping no longer exists" ); 201 202/// Frees the buffer's memory; it becomes empty. 203static void free_buff (StuffBuf * buf ) 204FUNC_ATTR_NONNULL_ALL 205{ 206kv_destroy (buf -> keys ); 207* buf = (StuffBuf ){0 }; 208} 209 210/// Gets the contents of the record buffer as a string (typeahead encoding) and clears the buffer. 211char * get_recorded (void ) 212{ 213size_t len = recordbuff .size ; 214kv_push (recordbuff ,NUL ); 215char * p = recordbuff .items ;// ownership moves to the caller 216recordbuff = (StringBuilder )KV_INITIAL_VALUE ; 217 218// Remove the characters that were added the last time, these must be the 219// (possibly mapped) characters that stopped the recording. 220if (len >=last_recorded_len ) { 221len -= last_recorded_len ; 222p [len ]= NUL ; 223 } 224 225// When stopping recording from Insert mode with CTRL-O q, also remove the 226// CTRL-O. 227if (len > 0 && restart_edit != 0 && p [len - 1 ]== Ctrl_O ) { 228p [len - 1 ]= NUL ; 229 } 230 231return p ; 232} 233 234/// Composes a `["x][count]` prefix from `spec` and appends it to `buf`. 235/// This is "Step 1" of redo-composition ("Step 2" is either `redobuff.cur.body` or `redo_chars`). 236/// 237/// @param replay Composing an actual replay (start_redo()): a `"=` register spec appends <CR>, 238/// re-evaluating the last expression. 239static void redo_prefix (const CmdSpec * spec ,StringBuilder * buf ,bool replay ) 240FUNC_ATTR_NONNULL_ARG (1 ) 241{ 242if (spec -> regname != 0 ) { 243sb_add_char (buf ,'"' ); 244sb_add_char (buf ,spec -> regname ); 245if (replay && spec -> regname == '=' ) { 246sb_add_char (buf ,CAR ); 247 } 248 } 249if (spec -> count != 0 ) { 250kv_printf (* buf ,"%d" , (int )spec -> count ); 251 } 252} 253 254/// Composes a command keysequence from `spec` and appends it to `buf`. 255/// This is "Step 2" of redo-composition ("Step 1" is `redo_prefix`). 256/// 257/// @param arg_meta Skip the `arg` byte (see prep_redo()). 258static void redo_chars (const CmdSpec * spec ,StringBuilder * buf ,bool arg_meta ) 259FUNC_ATTR_NONNULL_ALL 260{ 261if (spec -> op != NUL ) { 262sb_add_char (buf ,spec -> op ); 263 } 264if (spec -> op_extra != NUL ) { 265sb_add_char (buf ,spec -> op_extra ); 266 } 267if (spec -> motion_force != NUL ) { 268sb_add_char (buf ,spec -> motion_force ); 269 } 270if (spec -> cmd != NUL ) { 271sb_add_char (buf ,spec -> cmd ); 272 } 273if (spec -> cmd2 != NUL ) { 274sb_add_char (buf ,spec -> cmd2 ); 275 } 276if (spec -> cmdarg != NUL && !arg_meta ) { 277sb_add_char (buf ,spec -> cmdarg ); 278 } 279} 280 281/// Takes `buf`'s bytes as an allocated, NUL-terminated String, and clears `buf`. 282/// 283/// @return String; .data=NULL if `buf` is empty. 284static String sb_take_string (StringBuilder * buf ) 285FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 286{ 287if (buf -> size == 0 ) { 288kv_destroy (* buf ); 289return (String )STRING_INIT ; 290 } 291size_t len = buf -> size ; 292assert (buf -> items != NULL );// Coverity false-positive (already checked `size` above). 293kv_push (* buf ,NUL ); 294char * items = buf -> items ;// ownership moves to the caller 295* buf = (StringBuilder )KV_INITIAL_VALUE ; 296return cbuf_as_string (items ,len ); 297} 298 299/// Gets `spec` (or current pending change, if `spec` is NULL), composed into a "redo" keyseq 300/// `["x][count][body]`, where `[body]` is `spec.body`, or composed from the spec if body is empty. 301/// 302/// @return Allocated key sequence; .data == NULL if the result is empty. 303String redo_keys (const CmdSpec * spec ) 304FUNC_ATTR_WARN_UNUSED_RESULT 305{ 306spec = spec ?spec :& redobuff .cur ; 307 308StringBuilder buf = KV_INITIAL_VALUE ; 309redo_prefix (spec ,& buf , false); 310if (spec -> body .size > 0 ) { 311kv_splice (buf ,spec -> body ); 312 }else { 313redo_chars (spec ,& buf , false); 314 } 315return sb_take_string (& buf ); 316} 317 318/// Gets the pending change's CmdSpec (without `body`). 319CmdSpec redo_spec (void ) 320{ 321CmdSpec spec = redobuff .cur ; 322spec .body = (StringBuilder )KV_INITIAL_VALUE ; 323return spec ; 324} 325 326/// Inserts string `s` at `buf.insert`: the end, or ahead of not-yet-read keys (see start_stuff()). 327/// 328/// `s` must be in typeahead encoding, and must not point into `buf->keys`. 329/// 330/// @param slen String length, or -1 for a NUL-terminated string. 331static void add_buff (StuffBuf * const buf ,const char * const s ,ptrdiff_t slen ) 332{ 333if (slen < 0 ) { 334slen = (ptrdiff_t )strlen (s ); 335 } 336if (slen == 0 ) {// don't add empty strings 337return ; 338 } 339 340kv_ensure_space (buf -> keys , (size_t )slen ); 341char * at = buf -> keys .items + buf -> insert ; 342memmove (at + slen ,at ,buf -> keys .size - buf -> insert ); 343memcpy (at ,s , (size_t )slen ); 344buf -> keys .size += (size_t )slen ; 345buf -> insert += (size_t )slen ; 346} 347 348/// Append number "n" to buffer "buf". 349static void add_num_buff (StuffBuf * buf ,int n ) 350FUNC_ATTR_NONNULL_ALL 351{ 352char number [32 ]; 353int numberlen = snprintf (number ,sizeof (number ),"%d" ,n ); 354add_buff (buf ,number ,numberlen ); 355} 356 357/// Encodes byte or special key `c` into `temp`: the K_SPECIAL three-byte sequence for special 358/// keys, NUL and K_SPECIAL itself; the byte otherwise. 359/// 360/// @return Encoded length. 361static ptrdiff_t key_byte_encode (int c ,char temp [4 ]) 362FUNC_ATTR_NONNULL_ALL 363{ 364if (IS_SPECIAL (c )|| c == K_SPECIAL || c == NUL ) { 365// Translate special key code into three byte sequence. 366temp [0 ]= (char )K_SPECIAL ; 367temp [1 ]= (char )K_SECOND (c ); 368temp [2 ]= (char )K_THIRD (c ); 369temp [3 ]= NUL ; 370return 3 ; 371 } 372temp [0 ]= (char )c ; 373temp [1 ]= NUL ; 374return 1 ; 375} 376 377/// Encodes char `c` into `buf` (at least `MB_MAXBYTES * 3 + 1` bytes): a special key as its 378/// K_SPECIAL sequence, a multibyte char byte-wise with K_SPECIAL escaping. 379/// 380/// @return Encoded length. 381static size_t key_char_encode (int c ,char * buf ) 382FUNC_ATTR_NONNULL_ALL 383{ 384uint8_t bytes [MB_MAXBYTES + 1 ]; 385int len = IS_SPECIAL (c ) ?1 :utf_char2bytes (c , (char * )bytes ); 386size_t off = 0 ; 387for (int i = 0 ;i < len ;i ++ ) { 388off += (size_t )key_byte_encode (IS_SPECIAL (c ) ?c :bytes [i ],buf + off ); 389 } 390return off ; 391} 392 393/// Append character `c` to `buf`, translated to typeahead encoding. 394static void add_char_buff (StuffBuf * buf ,int c ) 395FUNC_ATTR_NONNULL_ALL 396{ 397char temp [MB_MAXBYTES * 3 + 1 ]; 398add_buff (buf ,temp , (ptrdiff_t )key_char_encode (c ,temp )); 399} 400 401/// Appends byte or special key `c` to `sb`. 402static void sb_add_byte (StringBuilder * sb ,int c ) 403FUNC_ATTR_NONNULL_ALL 404{ 405char temp [4 ]; 406size_t templen = (size_t )key_byte_encode (c ,temp ); 407kv_concat_len (* sb ,temp ,templen ); 408} 409 410/// Dual of add_char_buff(), for a StringBuilder. 411void sb_add_char (StringBuilder * sb ,int c ) 412FUNC_ATTR_NONNULL_ALL 413{ 414char temp [MB_MAXBYTES * 3 + 1 ]; 415size_t len = key_char_encode (c ,temp ); 416kv_concat_len (* sb ,temp ,len ); 417} 418 419/// Gets one byte (typeahead encoding, no translation) from the read buffers. Uses `readbuf1` one 420/// first, or `readbuf2` if that one is empty. 421/// 422/// @param advance Go to the next char. 423static int read_readbuffers (bool advance ) 424{ 425int c = read_readbuf (& readbuf1 ,advance ); 426if (c == NUL ) { 427c = read_readbuf (& readbuf2 ,advance ); 428 } 429return c ; 430} 431 432static int read_readbuf (StuffBuf * buf ,bool advance ) 433FUNC_ATTR_NONNULL_ALL 434{ 435if (buf -> read == buf -> keys .size ) {// buffer is empty 436return NUL ; 437 } 438 439uint8_t c = (uint8_t )buf -> keys .items [buf -> read ]; 440 441if (advance ) { 442buf -> read ++ ; 443if (buf -> read == buf -> keys .size ) {// drained: reset positions, keep capacity for reuse 444buf -> keys .size = 0 ; 445buf -> read = 0 ; 446buf -> insert = 0 ; 447 }else { 448buf -> insert = MAX (buf -> insert ,buf -> read ); 449 } 450 } 451return c ; 452} 453 454/// Makes the next stuffed text be read before the existing readahead. 455static void start_stuff (void ) 456{ 457readbuf1 .insert = readbuf1 .read ; 458readbuf2 .insert = readbuf2 .read ; 459} 460 461/// @return true if the readahead ("stuff") buffer is empty. 462bool stuff_empty (void ) 463FUNC_ATTR_PURE 464{ 465return readbuf1 .keys .size == 0 && readbuf2 .keys .size == 0 ; 466} 467 468/// @return true if readbuf1 is empty. There may still be redo characters in 469/// readbuf2. 470bool readbuf1_empty (void ) 471FUNC_ATTR_PURE 472{ 473return readbuf1 .keys .size == 0 ; 474} 475 476/// Set a typeahead character that won't be flushed. 477void typeahead_noflush (int c ) 478{ 479typeahead_char = c ; 480} 481 482/// Remove the contents of the stuff buffer and the mapped characters in the typeahead buffer (used 483/// in case of an error). 484/// 485/// @param flush_typeahead Flush all typeahead characters (used when interrupted by CTRL-C). 486void flush_buffers (flush_buffers_T flush_typeahead ) 487{ 488init_typebuf (); 489 490if (typebuf .tb_maplen > 0 ) { 491// Discarding a mapping's unconsumed keys: the mapping will never 492// complete, discard its subatoms. 493atom_composite_abort (); 494 } 495 496if (readbuf2 .keys .size > 0 && Visual .active ) { 497// This flush discards the dot-repeat keys, including the operator that would end the selection. 498// End Visual mode at cmd end, not here (else its autocmds would run inside emsg/vgetorpeek). 499Visual .need_end = true; 500 } 501free_buff (& readbuf1 ); 502free_buff (& readbuf2 ); 503 504if (flush_typeahead == FLUSH_MINIMAL ) { 505// remove mapped characters at the start only, 506// but only when enough space left in typebuf 507if (typebuf .tb_off + typebuf .tb_maplen >=typebuf .tb_buflen ) { 508typebuf .tb_off = MAXMAPLEN ; 509typebuf .tb_len = 0 ; 510 }else { 511typebuf .tb_off += typebuf .tb_maplen ; 512typebuf .tb_len -= typebuf .tb_maplen ; 513 } 514if (typebuf .tb_len == 0 ) { 515typebuf_was_filled = false; 516 } 517 }else { 518// remove typeahead 519if (flush_typeahead == FLUSH_INPUT ) { 520// We have to get all characters, because we may delete the first 521// part of an escape sequence. In an xterm we get one char at a 522// time and we have to get them all. 523while (inchar (typebuf .tb_buf ,typebuf .tb_buflen - 1 ,10 )!= 0 ) {} 524 } 525typebuf .tb_off = MAXMAPLEN ; 526typebuf .tb_len = 0 ; 527// Reset the flag that text received from a client or from feedkeys() 528// was inserted in the typeahead buffer. 529typebuf_was_filled = false; 530 } 531typebuf .tb_maplen = 0 ; 532typebuf .tb_silent = 0 ; 533cmd_silent = false; 534typebuf .tb_no_abbr_cnt = 0 ; 535if (++ typebuf .tb_change_cnt == 0 ) { 536typebuf .tb_change_cnt = 1 ; 537 } 538} 539 540/// flush map and typeahead buffers and give a warning for an error 541void beep_flush (void ) 542{ 543// Don't flush during mc-replay. A failed motion ("vt;" where there is no ";") should not eat 544// the keys typed after it ("c"). This matches Helix multiselection: each action during a Visual 545// selection proceeds or fails, without canceling the next action. 546if (emsg_silent == 0 && !mc_replaying ()) { 547flush_buffers (FLUSH_MINIMAL ); 548 } 549vim_beep (kOptBoFlagError ); 550} 551 552/// Starts capturing a new change: stores `spec`, caller appends the body (redo_append_x). The 553/// outgoing change moves to `redobuff.old`, which may be repeated by "CTRL-O ." in Insert mode, 554/// or restored by redo_cancel() if this change aborts. 555/// 556/// @param spec Structured command fields; zeroed if the caller only appends keys. 557void redo_new (CmdSpec spec ) 558{ 559assert (spec .body .size == 0 ); 560if (block_redo ) { 561return ; 562 } 563 564kv_destroy (redobuff .old .body ); 565redobuff .old = redobuff .cur ; 566redobuff .cur = spec ; 567} 568 569#ifdef EXITFREE 570/// Frees both redo buffers. 571void redo_free_all (void ) 572{ 573kv_destroy (redobuff .cur .body ); 574kv_destroy (redobuff .old .body ); 575redobuff = (RedoState ){0 }; 576} 577#endif 578 579/// Prepare for redo of any command: stores `spec` and appends its command chars. 580/// 581/// @param as_atom The redo also defines the command's atom (`CmdFrame.redo_frame`). False for 582/// "prep-exempt" special cases (insert-session entry/restart, "z="). 583/// @param arg_meta Skip the `arg` byte: an interactively-typed operand may need CTRL-V quoting 584/// or its composing-char string form, which the caller appends itself. 585void prep_redo (bool as_atom ,bool arg_meta ,CmdSpec spec ) 586{ 587if (as_atom ) { 588atom_redo_prepped (); 589 } 590redo_new (spec ); 591if (block_redo ) { 592return ; 593 } 594redo_chars (& spec ,& redobuff .cur .body ,arg_meta ); 595} 596 597/// Prepare for redo of a Visual-mode command: the body opens with `keys` (the captured selection), 598/// so "." re-executes the selection at cursor; the `["x][count]` prefix and command chars of 599/// `spec` compose into the body after them (zeroed in the stored spec, so replay doesn't also 600/// prefix them). 601void prep_redo_visual (const char * keys ,size_t len ,CmdSpec spec ) 602{ 603CmdSpec stored = spec ; 604stored .regname = 0 ; 605stored .count = 0 ; 606atom_redo_prepped (); 607redo_new (stored ); 608if (block_redo ) { 609return ; 610 } 611kv_concat_len (redobuff .cur .body ,keys ,len ); 612redo_prefix (& spec ,& redobuff .cur .body , false); 613redo_chars (& spec ,& redobuff .cur .body , false); 614} 615 616/// Discard the contents of the redo buffer and restore the previous redo 617/// buffer. 618void redo_cancel (void ) 619{ 620if (block_redo ) { 621return ; 622 } 623 624atom_redo_cancel (); 625kv_destroy (redobuff .cur .body ); 626redobuff .cur = redobuff .old ; 627redobuff .old = (CmdSpec ){0 }; 628free_buff (& readbuf1 ); 629free_buff (& readbuf2 ); 630} 631 632/// Saves the redo state to "save_redo" and detaches it. 633/// Used before executing autocommands and user functions. 634void save_redobuff (RedoState * save_redo ) 635FUNC_ATTR_NONNULL_ALL 636{ 637* save_redo = redobuff ; 638redobuff .cur .body = (StringBuilder )KV_INITIAL_VALUE ; 639redobuff .old = (CmdSpec ){0 }; 640 641// Make a copy (the fields stayed, copy the body), so that ":normal ." in a 642// function works. 643kv_splice (redobuff .cur .body ,save_redo -> cur .body ); 644} 645 646/// Restores the redo state from "save_redo". 647/// Used after executing autocommands and user functions. 648void restore_redobuff (RedoState * save_redo ) 649FUNC_ATTR_NONNULL_ALL 650{ 651kv_destroy (redobuff .cur .body ); 652kv_destroy (redobuff .old .body ); 653redobuff = * save_redo ; 654} 655 656/// Append `len` bytes of `s` (-1: up to the NUL) to the redo buffer. 657/// `s` must be in typeahead encoding. 658void redo_append_str (const char * s ,ptrdiff_t len ) 659{ 660if (!block_redo ) { 661size_t slen = len < 0 ?strlen (s ) : (size_t )len ; 662kv_concat_len (redobuff .cur .body ,s ,slen ); 663 } 664} 665 666/// Appends `str` to `buf` literally, escaping special characters with CTRL-V. 667/// K_SPECIAL is escaped as well. 668/// 669/// @param str String to append. 670/// @param len Length of `str` or -1 for up to the NUL. 671void sb_add_lit (StringBuilder * buf ,const char * str ,int len ) 672{ 673const char * s = str ; 674while (len < 0 ?* s != NUL :s - str < len ) { 675// Put a string of normal characters in the buffer (that's faster). 676const char * start = s ; 677while (* s >=' ' && * s < DEL && (len < 0 || s - str < len )) { 678s ++ ; 679 } 680 681// Don't put '0' or '^' as last character, just in case a CTRL-D is 682// typed next. 683if (* s == NUL && (s [-1 ]== '0' || s [-1 ]== '^' )) { 684s -- ; 685 } 686if (s > start ) { 687kv_concat_len (* buf ,start , (size_t )(s - start )); 688 } 689 690if (* s == NUL || (len >=0 && s - str >=len )) { 691break ; 692 } 693 694// Handle a special or multibyte character. 695// Composing chars separately are handled separately. 696const int c = mb_cptr2char_adv (& s ); 697if (c < ' ' || c == DEL || (* s == NUL && (c == '0' || c == '^' ))) { 698sb_add_char (buf ,Ctrl_V ); 699 } 700 701// CTRL-V '0' must be inserted as CTRL-V 048. 702if (* s == NUL && c == '0' ) { 703kv_concat_len (* buf ,"048" ,3 ); 704 }else { 705sb_add_char (buf ,c ); 706 } 707 } 708} 709 710/// Append to redo literally; no-op if `block_redo` is set; Insert dot-repeat consumes 711/// the redo buffer and must not append to it while doing so. 712void redo_append_lit (const char * str ,int len ) 713{ 714if (block_redo ) { 715return ; 716 } 717sb_add_lit (& redobuff .cur .body ,str ,len ); 718} 719 720/// Appends `s` to `buf`, leaving 3-byte special key codes unmodified and escaping other K_SPECIAL 721/// bytes. Unlike sb_add_lit(), no CTRL-V: for text read raw (<Cmd>), not typed into a cmdline. 722void sb_add_spec (StringBuilder * buf ,const char * s ) 723{ 724while (* s != NUL ) { 725if ((uint8_t )(* s )== K_SPECIAL && s [1 ]!= NUL && s [2 ]!= NUL ) { 726// Insert special key literally. 727kv_concat_len (* buf ,s ,3 ); 728s += 3 ; 729 }else { 730sb_add_char (buf ,mb_cptr2char_adv (& s )); 731 } 732 } 733} 734 735/// Append "s" to the redo buffer. 736void redo_append_spec (const char * s ) 737{ 738if (block_redo ) { 739return ; 740 } 741sb_add_spec (& redobuff .cur .body ,s ); 742} 743 744/// Appends character `c` to the redo buffer, translated to typeahead encoding. 745void redo_append_char (int c ) 746{ 747if (!block_redo ) { 748sb_add_char (& redobuff .cur .body ,c ); 749 } 750} 751 752/// Appends string `s` (must be typeahead encoding) to the stuff buffer. 753void stuffReadbuff (const char * s ) 754FUNC_ATTR_NONNULL_ALL 755{ 756add_buff (& readbuf1 ,s ,-1 ); 757} 758 759/// Appends string `s` (must be typeahead encoding) to the redo stuff buffer. 760void stuffRedoReadbuff (const char * s ) 761FUNC_ATTR_NONNULL_ALL 762{ 763add_buff (& readbuf2 ,s ,-1 ); 764} 765 766void stuffReadbuffLen (const char * s ,ptrdiff_t len ) 767{ 768if (add_last_insert == 1 ) {// Only add if this is the first call, for 769// recursive calls, ignore. 770ga_concat_len (& last_insert_ga ,s , (size_t )len ); 771 } 772add_buff (& readbuf1 ,s ,len ); 773} 774 775/// Stuff "s" into the stuff buffer, leaving special key codes unmodified and 776/// escaping other K_SPECIAL bytes. 777/// Change CR, LF and ESC into a space. 778void stuffReadbuffSpecial (const char * s ) 779FUNC_ATTR_NONNULL_ALL 780{ 781while (* s != NUL ) { 782if ((uint8_t )(* s )== K_SPECIAL && s [1 ]!= NUL && s [2 ]!= NUL ) { 783// Insert special key literally. 784stuffReadbuffLen (s ,3 ); 785s += 3 ; 786 }else { 787int c = mb_cptr2char_adv (& s ); 788if (c == CAR || c == NL || c == ESC ) { 789c = ' ' ; 790 } 791stuffcharReadbuff (c ); 792 } 793 } 794} 795 796/// Appends character `c` to the stuff buffer, translated to typeahead encoding. 797void stuffcharReadbuff (int c ) 798{ 799add_char_buff (& readbuf1 ,c ); 800} 801 802// Append a number to the stuff buffer. 803void stuffnumReadbuff (int n ) 804{ 805add_num_buff (& readbuf1 ,n ); 806} 807 808/// Stuff a string into the typeahead buffer, such that edit() will insert it 809/// literally ("literally" true) or interpret is as typed characters. 810void stuffescaped (const char * arg ,bool literally ) 811FUNC_ATTR_NONNULL_ALL 812{ 813while (* arg != NUL ) { 814// Stuff a sequence of normal ASCII characters, that's fast. Also 815// stuff K_SPECIAL to get the effect of a special key when "literally" 816// is true. 817const char * const start = arg ; 818while ((* arg >=' ' && * arg < DEL )|| ((uint8_t )(* arg )== K_SPECIAL 819&& !literally )) { 820arg ++ ; 821 } 822if (arg > start ) { 823stuffReadbuffLen (start ,arg - start ); 824 } 825 826// stuff a single special character 827if (* arg != NUL ) { 828const int c = mb_cptr2char_adv (& arg ); 829if (literally && ((c < ' ' && c != TAB )|| c == DEL )) { 830stuffcharReadbuff (Ctrl_V ); 831 } 832stuffcharReadbuff (c ); 833 } 834 } 835} 836 837/// Dot-repeat "." command: repeats the last change by composing the redo into readbuf2. "3." 838/// replaces count; a numbered-register redo increments regname ('"1p' then "." pastes '"2'), so "." 839/// steps through the delete history. A Visual-mode change re-executes its captured selection keys 840/// (embedded in the body, see prep_redo()). 841/// 842/// @param old_redo repeat the last-but-one change (i_CTRL-O ".": the insert 843/// session's own prep moved the last change to redobuff.old) 844/// @return FAIL for failure, OK otherwise 845int start_redo (int count ,bool old_redo ) 846{ 847CmdSpec * rd = old_redo ?& redobuff .old :& redobuff .cur ; 848if (rd -> body .size == 0 && rd -> regname == 0 && rd -> count == 0 ) { 849return FAIL ;// nothing to redo 850 } 851 852// Tweak the captured spec for replay: 853CmdSpec spec = * rd ; 854spec .body = (StringBuilder )KV_INITIAL_VALUE ; 855if (spec .regname >='1' && spec .regname < '9' ) { 856spec .regname ++ ;// numbered register: "." steps through the delete history 857 } 858if (count != 0 ) { 859spec .count = count ;// the new count replaces the captured one 860 } 861StringBuilder prefix = KV_INITIAL_VALUE ; 862redo_prefix (& spec ,& prefix , true); 863// coverity[var_deref_model] `items` is NULL only when size=0, which add_buff() ignores. 864add_buff (& readbuf2 ,prefix .items , (ptrdiff_t )prefix .size ); 865kv_destroy (prefix ); 866if (spec .regname == '=' ) { 867cmd_silent = true; 868 } 869 870add_buff (& readbuf2 ,rd -> body .items , (ptrdiff_t )rd -> body .size ); 871return OK ; 872} 873 874/// Repeats the last insert (R, o, O, a, A, i or I command) by stuffing the redo body's inserted 875/// text into readbuf2 (counted inserts: "3iZ<Esc>"). 876/// 877/// @return FAIL for failure, OK otherwise 878int start_redo_ins (void ) 879{ 880if (redobuff .cur .body .size == 0 ) { 881return FAIL ; 882 } 883start_stuff (); 884 885// Skip to the insert command; the rest of the keys is the inserted text. 886const char * p = redobuff .cur .body .items ; 887const char * const end = p + redobuff .cur .body .size ; 888while (p < end ) { 889if ((uint8_t )(* p )== K_SPECIAL && end - p >=3 ) { 890p += 3 ;// a special key is never the insert command 891continue ; 892 } 893if (vim_strchr ("AaIiRrOo" , (uint8_t )(* p ))!= NULL ) { 894if (* p == 'O' || * p == 'o' ) { 895add_buff (& readbuf2 ,NL_STR ,-1 ); 896 } 897p ++ ; 898break ; 899 } 900p ++ ; 901 } 902 903// copy the typed text from the redo buffer into the stuff buffer 904add_buff (& readbuf2 ,p ,end - p ); 905block_redo = true; 906return OK ; 907} 908 909void stop_redo_ins (void ) 910{ 911block_redo = false; 912} 913 914/// Initialize typebuf.tb_buf to point to typebuf_init. 915/// alloc() cannot be used here: In out-of-memory situations it would 916/// be impossible to type anything. 917static void init_typebuf (void ) 918{ 919if (typebuf .tb_buf != NULL ) { 920return ; 921 } 922 923typebuf .tb_buf = typebuf_init ; 924typebuf .tb_noremap = noremapbuf_init ; 925typebuf .tb_buflen = TYPELEN_INIT ; 926typebuf .tb_len = 0 ; 927typebuf .tb_off = MAXMAPLEN + 4 ; 928typebuf .tb_change_cnt = 1 ; 929} 930 931/// @return true when keys cannot be remapped. 932bool noremap_keys (void ) 933FUNC_ATTR_PURE 934{ 935return KeyNoremap & (RM_NONE |RM_SCRIPT ); 936} 937 938/// Insert a string in position "offset" in the typeahead buffer. 939/// 940/// If "noremap" is REMAP_YES, new string can be mapped again. 941/// If "noremap" is REMAP_NONE, new string cannot be mapped again. 942/// If "noremap" is REMAP_SKIP, first char of new string cannot be mapped again, 943/// but abbreviations are allowed. 944/// If "noremap" is REMAP_SCRIPT, new string cannot be mapped again, except for 945/// script-local mappings. 946/// If "noremap" is > 0, that many characters of the new string cannot be mapped. 947/// 948/// If "nottyped" is true, the string does not return KeyTyped (don't use when 949/// "offset" is non-zero!). 950/// 951/// If "silent" is true, cmd_silent is set when the characters are obtained. 952/// 953/// @return FAIL for failure, OK otherwise 954int ins_typebuf (char * str ,int noremap ,int offset ,bool nottyped ,bool silent ) 955FUNC_ATTR_NONNULL_ALL 956{ 957int val ; 958int nrm ; 959 960init_typebuf (); 961if (++ typebuf .tb_change_cnt == 0 ) { 962typebuf .tb_change_cnt = 1 ; 963 } 964state_no_longer_safe ("ins_typebuf()" ); 965 966int addlen = (int )strlen (str ); 967 968if (offset == 0 && addlen <=typebuf .tb_off ) { 969// Easy case: there is room in front of typebuf.tb_buf[typebuf.tb_off] 970typebuf .tb_off -= addlen ; 971memmove (typebuf .tb_buf + typebuf .tb_off ,str , (size_t )addlen ); 972 }else if (typebuf .tb_len == 0 973&& typebuf .tb_buflen >=addlen + 3 * (MAXMAPLEN + 4 )) { 974// Buffer is empty and string fits in the existing buffer. 975// Leave some space before and after, if possible. 976typebuf .tb_off = (typebuf .tb_buflen - addlen - 3 * (MAXMAPLEN + 4 )) /2 ; 977memmove (typebuf .tb_buf + typebuf .tb_off ,str , (size_t )addlen ); 978 }else { 979// Need to allocate a new buffer. 980// In typebuf.tb_buf there must always be room for 3 * (MAXMAPLEN + 4) 981// characters. We add some extra room to avoid having to allocate too 982// often. 983int newoff = MAXMAPLEN + 4 ; 984int extra = addlen + newoff + 4 * (MAXMAPLEN + 4 ); 985if (typebuf .tb_len > INT_MAX - extra ) { 986// string is getting too long for 32 bit int 987emsg (_ (e_command_too_complex ));// also calls flush_buffers 988setcursor (); 989return FAIL ; 990 } 991int newlen = typebuf .tb_len + extra ; 992uint8_t * s1 = xmalloc ((size_t )newlen ); 993uint8_t * s2 = xmalloc ((size_t )newlen ); 994typebuf .tb_buflen = newlen ; 995 996// copy the old chars, before the insertion point 997memmove (s1 + newoff ,typebuf .tb_buf + typebuf .tb_off , (size_t )offset ); 998// copy the new chars 999memmove (s1 + newoff + offset ,str , (size_t )addlen ); 1000// copy the old chars, after the insertion point, including the NUL at 1001// the end 1002int bytes = typebuf .tb_len - offset + 1 ; 1003assert (bytes > 0 ); 1004memmove (s1 + newoff + offset + addlen , 1005typebuf .tb_buf + typebuf .tb_off + offset , (size_t )bytes ); 1006if (typebuf .tb_buf != typebuf_init ) { 1007xfree (typebuf .tb_buf ); 1008 } 1009typebuf .tb_buf = s1 ; 1010 1011memmove (s2 + newoff ,typebuf .tb_noremap + typebuf .tb_off , 1012 (size_t )offset ); 1013memmove (s2 + newoff + offset + addlen , 1014typebuf .tb_noremap + typebuf .tb_off + offset , 1015 (size_t )(typebuf .tb_len - offset )); 1016if (typebuf .tb_noremap != noremapbuf_init ) { 1017xfree (typebuf .tb_noremap ); 1018 } 1019typebuf .tb_noremap = s2 ; 1020 1021typebuf .tb_off = newoff ; 1022 } 1023typebuf .tb_len += addlen ; 1024 1025// If noremap == REMAP_SCRIPT: do remap script-local mappings. 1026if (noremap == REMAP_SCRIPT ) { 1027val = RM_SCRIPT ; 1028 }else if (noremap == REMAP_SKIP ) { 1029val = RM_ABBR ; 1030 }else { 1031val = RM_NONE ; 1032 } 1033 1034// Adjust typebuf.tb_noremap[] for the new characters: 1035// If noremap == REMAP_NONE or REMAP_SCRIPT: new characters are 1036// (sometimes) not remappable 1037// If noremap == REMAP_YES: all the new characters are mappable 1038// If noremap > 0: "noremap" characters are not remappable, the rest 1039// mappable 1040if (noremap == REMAP_SKIP ) { 1041nrm = 1 ; 1042 }else if (noremap < 0 ) { 1043nrm = addlen ; 1044 }else { 1045nrm = noremap ; 1046 } 1047for (int i = 0 ;i < addlen ;i ++ ) { 1048typebuf .tb_noremap [typebuf .tb_off + i + offset ]= 1049 (uint8_t )((-- nrm >=0 ) ?val :RM_YES ); 1050 } 1051 1052// tb_maplen and tb_silent only remember the length of mapped and/or 1053// silent mappings at the start of the buffer, assuming that a mapped 1054// sequence doesn't result in typed characters. 1055if (nottyped || typebuf .tb_maplen > offset ) { 1056typebuf .tb_maplen += addlen ; 1057 } 1058if (silent || typebuf .tb_silent > offset ) { 1059typebuf .tb_silent += addlen ; 1060cmd_silent = true; 1061 } 1062if (typebuf .tb_no_abbr_cnt && offset == 0 ) {// and not used for abbrev.s 1063typebuf .tb_no_abbr_cnt += addlen ; 1064 } 1065 1066return OK ; 1067} 1068 1069/// Re-queues key `c`: puts a key obtained by vgetc() back into typeahead, to be reprocessed: mapped 1070/// (cf. vungetc(), which bypasses mapping), recorded and reported. Calls ungetchars() to drop the 1071/// effects of consuming it the first time. 1072/// 1073/// Uses cmd_silent, KeyTyped and KeyNoremap to restore the flags belonging to the char. 1074/// 1075/// @param recorded Pass false if the caller suppressed recording on the initial read. 1076/// @param extra_consumed Extra consumed bytes to un-record beyond the key itself (vgetc()'s 1077/// ALT-rewrite consumed a `K_SPECIAL KS_MODIFIER` prefix too). 1078void requeue_key (int c ,int modifiers ,int extra_consumed ,bool recorded ) 1079{ 1080char buf [MB_MAXBYTES * 3 + 4 ]; 1081unsigned len = special_to_buf (c ,modifiers , true,buf ); 1082assert (len < sizeof (buf )); 1083buf [len ]= NUL ; 1084ins_typebuf (buf ,KeyNoremap ,0 , !KeyTyped ,cmd_silent ); 1085ungetchars ((int )len + extra_consumed ,recorded ); 1086} 1087 1088/// Return true if the typeahead buffer was changed (while waiting for a 1089/// character to arrive). Happens when a message was received from a client or 1090/// from feedkeys(). 1091/// But check in a more generic way to avoid trouble: When "typebuf.tb_buf" 1092/// changed it was reallocated and the old pointer can no longer be used. 1093/// Or "typebuf.tb_off" may have been changed and we would overwrite characters 1094/// that was just added. 1095/// 1096/// @param tb_change_cnt old value of typebuf.tb_change_cnt 1097bool typebuf_changed (int tb_change_cnt ) 1098FUNC_ATTR_PURE 1099{ 1100return tb_change_cnt != 0 && (typebuf .tb_change_cnt != tb_change_cnt 1101|| typebuf_was_filled ); 1102} 1103 1104/// Return true if there are no characters in the typeahead buffer that have 1105/// not been typed (result from a mapping or come from ":normal"). 1106int typebuf_typed (void ) 1107FUNC_ATTR_PURE 1108{ 1109return typebuf .tb_maplen == 0 ; 1110} 1111 1112/// Get the number of characters that are mapped (or not typed). 1113int typebuf_maplen (void ) 1114FUNC_ATTR_PURE 1115{ 1116return typebuf .tb_maplen ; 1117} 1118 1119/// Remove "len" characters from typebuf.tb_buf[typebuf.tb_off + offset] 1120void del_typebuf (int len ,int offset ) 1121{ 1122if (len == 0 ) { 1123return ;// nothing to do 1124 } 1125 1126typebuf .tb_len -= len ; 1127 1128// Easy case: Just increase typebuf.tb_off. 1129if (offset == 0 && typebuf .tb_buflen - (typebuf .tb_off + len ) 1130 >=3 * MAXMAPLEN + 3 ) { 1131typebuf .tb_off += len ; 1132 }else { 1133// Have to move the characters in typebuf.tb_buf[] and typebuf.tb_noremap[] 1134int i = typebuf .tb_off + offset ; 1135// Leave some extra room at the end to avoid reallocation. 1136if (typebuf .tb_off > MAXMAPLEN ) { 1137memmove (typebuf .tb_buf + MAXMAPLEN , 1138typebuf .tb_buf + typebuf .tb_off , (size_t )offset ); 1139memmove (typebuf .tb_noremap + MAXMAPLEN , 1140typebuf .tb_noremap + typebuf .tb_off , (size_t )offset ); 1141typebuf .tb_off = MAXMAPLEN ; 1142 } 1143// adjust typebuf.tb_buf (include the NUL at the end) 1144int bytes = typebuf .tb_len - offset + 1 ; 1145assert (bytes > 0 ); 1146memmove (typebuf .tb_buf + typebuf .tb_off + offset , 1147typebuf .tb_buf + i + len , (size_t )bytes ); 1148// adjust typebuf.tb_noremap[] 1149memmove (typebuf .tb_noremap + typebuf .tb_off + offset , 1150typebuf .tb_noremap + i + len , 1151 (size_t )(typebuf .tb_len - offset )); 1152 } 1153 1154if (typebuf .tb_maplen > offset ) {// adjust tb_maplen 1155if (typebuf .tb_maplen < offset + len ) { 1156typebuf .tb_maplen = offset ; 1157 }else { 1158typebuf .tb_maplen -= len ; 1159 } 1160 } 1161if (typebuf .tb_silent > offset ) {// adjust tb_silent 1162if (typebuf .tb_silent < offset + len ) { 1163typebuf .tb_silent = offset ; 1164 }else { 1165typebuf .tb_silent -= len ; 1166 } 1167 } 1168if (typebuf .tb_no_abbr_cnt > offset ) {// adjust tb_no_abbr_cnt 1169if (typebuf .tb_no_abbr_cnt < offset + len ) { 1170typebuf .tb_no_abbr_cnt = offset ; 1171 }else { 1172typebuf .tb_no_abbr_cnt -= len ; 1173 } 1174 } 1175 1176// Reset the flag that text received from a client or from feedkeys() 1177// was inserted in the typeahead buffer. 1178typebuf_was_filled = false; 1179if (++ typebuf .tb_change_cnt == 0 ) { 1180typebuf .tb_change_cnt = 1 ; 1181 } 1182} 1183 1184/// Append a single byte to a recording or 'showcmd'. 1185/// Return true if a full key has been received, false otherwise. 1186static bool gotchars_add_byte (gotchars_state_T * state ,uint8_t byte ) 1187FUNC_ATTR_NONNULL_ALL 1188{ 1189int c = state -> buf [state -> buflen ++ ]= byte ; 1190bool retval = false; 1191const bool in_special = state -> pending_special > 0 ; 1192const bool in_mbyte = state -> pending_mbyte > 0 ; 1193 1194if (in_special ) { 1195state -> pending_special -- ; 1196 }else if (c == K_SPECIAL ) { 1197// When receiving a special key sequence, store it until we have all 1198// the bytes and we can decide what to do with it. 1199state -> pending_special = 2 ; 1200 } 1201 1202if (state -> pending_special > 0 ) { 1203 gotoret_false ; 1204 } 1205 1206if (in_mbyte ) { 1207state -> pending_mbyte -- ; 1208 }else { 1209if (in_special ) { 1210if (state -> prev_c == KS_MODIFIER ) { 1211// When receiving a modifier, wait for the modified key. 1212 gotoret_false ; 1213 } 1214c = TO_SPECIAL (state -> prev_c ,c ); 1215// Drop K_COMPLETE_DELAY, it's not useful in a recording. 1216if (c == K_COMPLETE_DELAY ) { 1217state -> buflen = 0 ; 1218 } 1219 } 1220// When receiving a multibyte character, store it until we have all the bytes, so that 1221// whole keys reach the recording and ungetchars() removes whole keys. 1222state -> pending_mbyte = MB_BYTE2LEN_CHECK (c )- 1 ; 1223 } 1224 1225if (state -> pending_mbyte > 0 ) { 1226 gotoret_false ; 1227 } 1228 1229retval = true; 1230ret_false : 1231state -> prev_c = c ; 1232return retval ; 1233} 1234 1235/// Write typed characters to script file. 1236/// If recording is on put the character in the record buffer. 1237static void gotchars (const uint8_t * chars ,size_t len ) 1238FUNC_ATTR_NONNULL_ALL 1239{ 1240const uint8_t * s = chars ; 1241size_t todo = len ; 1242static gotchars_state_T state ; 1243 1244while (todo -- > 0 ) { 1245if (!gotchars_add_byte (& state ,* s ++ )) { 1246continue ; 1247 } 1248 1249// Handle one byte at a time; no translation to be done. 1250for (size_t i = 0 ;i < state .buflen ;i ++ ) { 1251updatescript (state .buf [i ]); 1252 } 1253 1254if (state .buflen > on_key_ignore_len ) { 1255kvi_concat_len (on_key_buf , (char * )state .buf + on_key_ignore_len , 1256state .buflen - on_key_ignore_len ); 1257on_key_ignore_len = 0 ; 1258 }else { 1259on_key_ignore_len -= state .buflen ; 1260 } 1261 1262if (reg_recording != 0 ) { 1263kv_concat_len (recordbuff , (char * )state .buf ,state .buflen ); 1264// remember how many chars were last recorded 1265last_recorded_len += state .buflen ; 1266 } 1267 1268// Typed keys consumed during 'operatorfunc' are the op's interactive payload. 1269atom_typed_add (state .buf ,state .buflen ); 1270 1271state .buflen = 0 ; 1272 } 1273 1274may_sync_undo (); 1275 1276// output "debug mode" message next time in debug mode 1277debug_did_msg = false; 1278 1279// Since characters have been typed, consider the following to be in 1280// another mapping. Search string will be kept in history. 1281maptick ++ ; 1282} 1283 1284/// Record an <Ignore> key. 1285void gotchars_ignore (void ) 1286{ 1287uint8_t nop_buf [3 ]= {K_SPECIAL ,KS_EXTRA ,KE_IGNORE }; 1288on_key_ignore_len += 3 ; 1289gotchars (nop_buf ,3 ); 1290} 1291 1292/// Undo the last gotchars() for `len` bytes: a key that was read is being re-queued into typeahead, 1293/// so it will be read (+ gotchars()) again. Un-reports the bytes, and (if `recorded`) removes them 1294/// from the recording. 1295/// 1296/// @param recorded Pass false if recording was suppressed on the first read: the trailing 1297/// `recordbuff` bytes are unrelated and deleting them would corrupt it. 1298static void ungetchars (int len ,bool recorded ) 1299{ 1300if (!KeyTyped ) { 1301return ;// gotchars() only sees typed keys; nothing to undo. 1302 } 1303if (recorded && reg_recording != 0 && recordbuff .size >= (size_t )len ) { 1304recordbuff .size -= (size_t )len ; 1305last_recorded_len -= (size_t )len ; 1306 } 1307atom_typed_del ((size_t )len ); 1308size_t trim = MIN ((size_t )len ,on_key_buf .size ); 1309on_key_buf .size -= trim ; 1310on_key_ignore_len += (size_t )len - trim ; 1311} 1312 1313/// Sync undo. Called when typed characters are obtained from the typeahead 1314/// buffer, or when a menu is used. 1315/// Do not sync: 1316/// - In Insert mode, unless cursor key has been used. 1317/// - While reading a script file. 1318/// - When no_u_sync is non-zero. 1319void may_sync_undo (void ) 1320{ 1321if ((!(State & (MODE_INSERT |MODE_CMDLINE ))|| Ins .moved != kInsNone ) 1322&& curscript < 0 ) { 1323u_sync (false); 1324 } 1325} 1326 1327/// Make "typebuf" empty and allocate new buffers. 1328static void alloc_typebuf (void ) 1329{ 1330typebuf .tb_buf = xmalloc (TYPELEN_INIT ); 1331typebuf .tb_noremap = xmalloc (TYPELEN_INIT ); 1332typebuf .tb_buflen = TYPELEN_INIT ; 1333typebuf .tb_off = MAXMAPLEN + 4 ;// can insert without realloc 1334typebuf .tb_len = 0 ; 1335typebuf .tb_maplen = 0 ; 1336typebuf .tb_silent = 0 ; 1337typebuf .tb_no_abbr_cnt = 0 ; 1338if (++ typebuf .tb_change_cnt == 0 ) { 1339typebuf .tb_change_cnt = 1 ; 1340 } 1341typebuf_was_filled = false; 1342} 1343 1344/// Free the buffers of "typebuf". 1345static void free_typebuf (void ) 1346{ 1347if (typebuf .tb_buf == typebuf_init ) { 1348internal_error ("Free typebuf 1" ); 1349 }else { 1350XFREE_CLEAR (typebuf .tb_buf ); 1351 } 1352if (typebuf .tb_noremap == noremapbuf_init ) { 1353internal_error ("Free typebuf 2" ); 1354 }else { 1355XFREE_CLEAR (typebuf .tb_noremap ); 1356 } 1357} 1358 1359/// When doing ":so! file", the current typeahead needs to be saved, and 1360/// restored when "file" has been read completely. 1361static typebuf_T saved_typebuf [NSCRIPT ]; 1362 1363static void save_typebuf (void ) 1364{ 1365assert (curscript >=0 ); 1366init_typebuf (); 1367saved_typebuf [curscript ]= typebuf ; 1368alloc_typebuf (); 1369} 1370 1371static bool can_get_ungot (void ) 1372FUNC_ATTR_PURE 1373{ 1374// If the ungotten character was not stuffed and characters have been added to 1375// the stuff buffer, need to first get the stuffed characters instead. 1376return ungot .c != -1 && (ungot .stuffed || stuff_empty ()); 1377} 1378 1379/// Save all three kinds of typeahead, so that the user must type at a prompt. 1380void save_typeahead (tasave_T * tp ) 1381FUNC_ATTR_NONNULL_ALL 1382{ 1383tp -> save_typebuf = typebuf ; 1384alloc_typebuf (); 1385tp -> ungot = ungot ; 1386ungot .c = -1 ; 1387 1388tp -> save_readbuf1 = readbuf1 ; 1389readbuf1 = (StuffBuf ){0 }; 1390tp -> save_readbuf2 = readbuf2 ; 1391readbuf2 = (StuffBuf ){0 }; 1392} 1393 1394/// Restore the typeahead to what it was before calling save_typeahead(). 1395/// The allocated memory is freed, can only be called once! 1396void restore_typeahead (tasave_T * tp ) 1397FUNC_ATTR_NONNULL_ALL 1398{ 1399free_typebuf (); 1400typebuf = tp -> save_typebuf ; 1401ungot = tp -> ungot ; 1402 1403free_buff (& readbuf1 ); 1404readbuf1 = tp -> save_readbuf1 ; 1405free_buff (& readbuf2 ); 1406readbuf2 = tp -> save_readbuf2 ; 1407} 1408 1409/// Open a new script file for the ":source!" command. 1410/// 1411/// @param directly when true execute directly 1412void openscript (char * name ,bool directly ) 1413{ 1414if (curscript + 1 == NSCRIPT ) { 1415emsg (_ (e_nesting )); 1416return ; 1417 } 1418 1419// Disallow sourcing a file in the sandbox, the commands would be executed 1420// later, possibly outside of the sandbox. 1421if (check_secure ()) { 1422return ; 1423 } 1424 1425if (ignore_script ) { 1426// Not reading from script, also don't open one. Warning message? 1427return ; 1428 } 1429 1430curscript ++ ; 1431// use NameBuff for expanded name 1432expand_env (name ,NameBuff ,MAXPATHL ); 1433int error = file_open (& scriptin [curscript ],NameBuff ,kFileReadOnly ,0 ); 1434if (error ) { 1435semsg (_ (e_notopen_2 ),name ,os_strerror (error )); 1436curscript -- ; 1437return ; 1438 } 1439save_typebuf (); 1440 1441// Execute the commands from the file right now when using ":source!" 1442// after ":global" or ":argdo" or in a loop. Also when another command 1443// follows. This means the display won't be updated. Don't do this 1444// always, "make test" would fail. 1445if (directly ) { 1446oparg_T oa ; 1447int save_State = State ; 1448int save_restart_edit = restart_edit ; 1449int save_finish_op = finish_op ; 1450int save_msg_scroll = msg_scroll ; 1451 1452State = MODE_NORMAL ; 1453msg_scroll = false;// no msg scrolling in Normal mode 1454restart_edit = 0 ;// don't go to Insert mode 1455clear_oparg (& oa ); 1456finish_op = false; 1457 1458int oldcurscript = curscript ; 1459do { 1460update_topline_cursor ();// update cursor position and topline 1461normal_cmd (& oa , false);// execute one command 1462vpeekc ();// check for end of file 1463 }while (curscript >=oldcurscript ); 1464 1465State = save_State ; 1466msg_scroll = save_msg_scroll ; 1467restart_edit = save_restart_edit ; 1468finish_op = save_finish_op ; 1469 } 1470} 1471 1472/// Close the currently active input script. 1473static void closescript (void ) 1474{ 1475assert (curscript >=0 ); 1476free_typebuf (); 1477typebuf = saved_typebuf [curscript ]; 1478 1479file_close (& scriptin [curscript ], false); 1480curscript -- ; 1481} 1482 1483#ifdef EXITFREE 1484void close_all_scripts (void ) 1485{ 1486while (curscript >=0 ) { 1487closescript (); 1488 } 1489} 1490 1491#endif 1492 1493bool open_scriptin (char * scriptin_name ) 1494FUNC_ATTR_NONNULL_ALL 1495{ 1496assert (curscript == -1 ); 1497curscript ++ ; 1498 1499int error ; 1500if (strequal (scriptin_name ,"-" )) { 1501error = file_open_stdin (& scriptin [0 ]); 1502 }else { 1503error = file_open (& scriptin [0 ],scriptin_name , 1504kFileReadOnly |kFileNonBlocking ,0 ); 1505 } 1506if (error ) { 1507fprintf (stderr ,_ ("Cannot open for reading: \"%s\": %s\n" ), 1508scriptin_name ,os_strerror (error )); 1509curscript -- ; 1510return false; 1511 } 1512save_typebuf (); 1513 1514return true; 1515} 1516 1517/// Return true when reading keys from a script file. 1518int using_script (void ) 1519FUNC_ATTR_PURE 1520{ 1521return curscript >=0 ; 1522} 1523 1524/// This function is called just before doing a blocking wait. Thus after 1525/// waiting 'updatetime' for a character to arrive. 1526void before_blocking (void ) 1527{ 1528updatescript (0 ); 1529if (may_garbage_collect ) { 1530garbage_collect (false); 1531 } 1532} 1533 1534/// updatescript() is called when a character can be written to the script 1535/// file or when we have waited some time for a character (c == 0). 1536/// 1537/// All the changed memfiles are synced if c == 0 or when the number of typed 1538/// characters reaches 'updatecount' and 'updatecount' is non-zero. 1539static void updatescript (int c ) 1540{ 1541static int count = 0 ; 1542 1543if (c && scriptout ) { 1544putc (c ,scriptout ); 1545 } 1546bool idle = (c == 0 ); 1547if (idle || (p_uc > 0 && ++ count >=p_uc )) { 1548ml_sync_all (idle , true, 1549 (!!p_fs || idle ));// Always fsync at idle (CursorHold). 1550count = 0 ; 1551 } 1552} 1553 1554/// Merge "modifiers" into "c_arg". 1555int merge_modifiers (int c_arg ,int * modifiers ) 1556FUNC_ATTR_NONNULL_ALL 1557{ 1558int c = c_arg ; 1559 1560if (* modifiers & MOD_MASK_CTRL ) { 1561if (c >='@' && c <=0x7f ) { 1562c &=0x1f ; 1563if (c == NUL ) { 1564c = K_ZERO ; 1565 } 1566 }else if (c == '6' ) { 1567// CTRL-6 is equivalent to CTRL-^ 1568c = 0x1e ; 1569 } 1570if (c != c_arg ) { 1571* modifiers &= ~MOD_MASK_CTRL ; 1572 } 1573 } 1574return c ; 1575} 1576 1577/// Append a single byte to 'showcmd' for a partially matched mapping. 1578/// Call add_to_showcmd() if a full key has been received. 1579static void add_byte_to_showcmd (uint8_t byte ) 1580{ 1581static gotchars_state_T state ; 1582 1583if (!p_sc || msg_silent != 0 ) { 1584return ; 1585 } 1586 1587if (!gotchars_add_byte (& state ,byte )) { 1588return ; 1589 } 1590 1591state .buf [state .buflen ]= NUL ; 1592state .buflen = 0 ; 1593 1594int modifiers = 0 ; 1595int c = NUL ; 1596 1597const uint8_t * ptr = state .buf ; 1598if (ptr [0 ]== K_SPECIAL && ptr [1 ]== KS_MODIFIER && ptr [2 ]!= NUL ) { 1599modifiers = ptr [2 ]; 1600ptr += 3 ; 1601 } 1602 1603if (* ptr != NUL ) { 1604const char * mb_ptr = mb_unescape ((const char ** )& ptr ); 1605c = mb_ptr != NULL ?utf_ptr2char (mb_ptr ) :* ptr ++ ; 1606if (c <=0x7f ) { 1607// Merge modifiers into the key to make the result more readable. 1608int modifiers_after = modifiers ; 1609int mod_c = merge_modifiers (c ,& modifiers_after ); 1610if (modifiers_after == 0 ) { 1611modifiers = 0 ; 1612c = mod_c ; 1613 } 1614 } 1615 } 1616 1617// TODO(zeertzjq): is there a more readable and yet compact representation of 1618// modifiers and special keys? 1619if (modifiers != 0 ) { 1620add_to_showcmd (K_SPECIAL ); 1621add_to_showcmd (KS_MODIFIER ); 1622add_to_showcmd (modifiers ); 1623 } 1624if (c != NUL ) { 1625add_to_showcmd (c ); 1626 } 1627while (* ptr != NUL ) { 1628add_to_showcmd (* ptr ++ ); 1629 } 1630} 1631 1632/// Get the next input character. 1633/// Can return a special key or a multi-byte character. 1634/// Can return NUL when called recursively, use safe_vgetc() if that's not 1635/// wanted. 1636/// This translates escaped K_SPECIAL bytes to a K_SPECIAL byte. 1637/// Collects the bytes of a multibyte character into the whole character. 1638/// Returns the modifiers in the global "mod_mask". 1639int vgetc (void ) 1640{ 1641int c ; 1642uint8_t buf [MB_MAXBYTES + 1 ]; 1643 1644// Do garbage collection when garbagecollect() was called previously and 1645// we are now at the toplevel. 1646if (may_garbage_collect && want_garbage_collect ) { 1647garbage_collect (false); 1648 } 1649 1650// If a character was put back with vungetc, it was already processed. 1651// Return it directly. 1652if (can_get_ungot ()) { 1653c = ungot .c ; 1654ungot .c = -1 ; 1655mod_mask = ungot .mod_mask ; 1656mouse_grid = ungot .mouse_grid ; 1657mouse_row = ungot .mouse_row ; 1658mouse_col = ungot .mouse_col ; 1659 }else { 1660// number of characters recorded from the last vgetc() call 1661static size_t last_vgetc_recorded_len = 0 ; 1662 1663mod_mask = 0 ; 1664vgetc_mod_mask = 0 ; 1665vgetc_char = 0 ; 1666 1667// last_recorded_len can be larger than last_vgetc_recorded_len 1668// if peeking records more 1669last_recorded_len -= last_vgetc_recorded_len ; 1670 1671while (true) {// this is done twice if there are modifiers 1672bool did_inc = false; 1673if (mod_mask ) {// no mapping after modifier has been read 1674no_mapping ++ ; 1675allow_keys ++ ; 1676did_inc = true;// mod_mask may change value 1677 } 1678c = vgetorpeek (true); 1679if (did_inc ) { 1680no_mapping -- ; 1681allow_keys -- ; 1682 } 1683 1684// Get two extra bytes for special keys 1685if (c == K_SPECIAL ) { 1686int save_allow_keys = allow_keys ; 1687no_mapping ++ ; 1688allow_keys = 0 ;// make sure BS is not found 1689int c2 = vgetorpeek (true);// no mapping for these chars 1690c = vgetorpeek (true); 1691no_mapping -- ; 1692allow_keys = save_allow_keys ; 1693if (c2 == KS_MODIFIER ) { 1694mod_mask = c ; 1695continue ; 1696 } 1697c = TO_SPECIAL (c2 ,c ); 1698 } 1699 1700// For a multi-byte character get all the bytes and return the 1701// converted character. 1702// Note: This will loop until enough bytes are received! 1703int n ; 1704if ((n = MB_BYTE2LEN_CHECK (c ))> 1 ) { 1705no_mapping ++ ; 1706buf [0 ]= (uint8_t )c ; 1707for (int i = 1 ;i < n ;i ++ ) { 1708buf [i ]= (uint8_t )vgetorpeek (true); 1709if (buf [i ]== K_SPECIAL ) { 1710// Must be a K_SPECIAL - KS_SPECIAL - KE_FILLER sequence, 1711// which represents a K_SPECIAL (0x80). 1712vgetorpeek (true);// skip KS_SPECIAL 1713vgetorpeek (true);// skip KE_FILLER 1714 } 1715 } 1716no_mapping -- ; 1717c = utf_ptr2char ((char * )buf ); 1718 } 1719 1720// If mappings are enabled (i.e., not i_CTRL-V) and the user directly typed 1721// something with MOD_MASK_ALT (<M-/<A- modifier) that was not mapped, interpret 1722// <M-x> as <Esc>x rather than as an unbound <M-x> keypress. #8213 1723// In Terminal mode, however, this is not desirable. #16202 #16220 1724// Also do not do this for mouse keys, as terminals encode mouse events as 1725// CSI sequences, and MOD_MASK_ALT has a meaning even for unmapped mouse keys. 1726if (!no_mapping && KeyTyped && mod_mask == MOD_MASK_ALT 1727&& !(State & MODE_TERMINAL )&& !is_mouse_key (c )) { 1728mod_mask = 0 ; 1729// Un-record/un-report the consumed <M-x> (its K_SPECIAL KS_MODIFIER MOD_MASK_ALT prefix 1730// took 3 more bytes); the rewritten <Esc>x is consumed (recorded, reported) in its place. 1731requeue_key (c ,0 ,3 , true); 1732ins_typebuf (ESC_STR ,KeyNoremap ,0 , !KeyTyped ,cmd_silent ); 1733continue ; 1734 } 1735 1736if (vgetc_char == 0 ) { 1737vgetc_mod_mask = mod_mask ; 1738vgetc_char = c ; 1739 } 1740 1741// A keypad or special function key was not mapped, use it like 1742// its ASCII equivalent. 1743switch (c ) { 1744case K_KPLUS : 1745c = '+' ;break ; 1746case K_KMINUS : 1747c = '-' ;break ; 1748case K_KDIVIDE : 1749c = '/' ;break ; 1750case K_KMULTIPLY : 1751c = '*' ;break ; 1752case K_KENTER : 1753c = CAR ;break ; 1754case K_KPOINT : 1755c = '.' ;break ; 1756case K_KCOMMA : 1757c = ',' ;break ; 1758case K_KEQUAL : 1759c = '=' ;break ; 1760case K_K0 : 1761c = '0' ;break ; 1762case K_K1 : 1763c = '1' ;break ; 1764case K_K2 : 1765c = '2' ;break ; 1766case K_K3 : 1767c = '3' ;break ; 1768case K_K4 : 1769c = '4' ;break ; 1770case K_K5 : 1771c = '5' ;break ; 1772case K_K6 : 1773c = '6' ;break ; 1774case K_K7 : 1775c = '7' ;break ; 1776case K_K8 : 1777c = '8' ;break ; 1778case K_K9 : 1779c = '9' ;break ; 1780 1781case K_XHOME : 1782case K_ZHOME : 1783if (mod_mask == MOD_MASK_SHIFT ) { 1784c = K_S_HOME ; 1785mod_mask = 0 ; 1786 }else if (mod_mask == MOD_MASK_CTRL ) { 1787c = K_C_HOME ; 1788mod_mask = 0 ; 1789 }else { 1790c = K_HOME ; 1791 } 1792break ; 1793case K_XEND : 1794case K_ZEND : 1795if (mod_mask == MOD_MASK_SHIFT ) { 1796c = K_S_END ; 1797mod_mask = 0 ; 1798 }else if (mod_mask == MOD_MASK_CTRL ) { 1799c = K_C_END ; 1800mod_mask = 0 ; 1801 }else { 1802c = K_END ; 1803 } 1804break ; 1805 1806case K_KUP : 1807case K_XUP : 1808c = K_UP ;break ; 1809case K_KDOWN : 1810case K_XDOWN : 1811c = K_DOWN ;break ; 1812case K_KLEFT : 1813case K_XLEFT : 1814c = K_LEFT ;break ; 1815case K_KRIGHT : 1816case K_XRIGHT : 1817c = K_RIGHT ;break ; 1818 } 1819 1820break ; 1821 } 1822 1823last_vgetc_recorded_len = last_recorded_len ; 1824 } 1825 1826// In the main loop "may_garbage_collect" can be set to do garbage 1827// collection in the first next vgetc(). It's disabled after that to 1828// avoid internally used Lists and Dicts to be freed. 1829may_garbage_collect = false; 1830 1831// Execute Lua on_key callbacks. 1832kvi_push (on_key_buf ,NUL ); 1833if (getchar_depth == 0 && nlua_exec_on_key (c ,on_key_buf .items )) { 1834// Keys following K_COMMAND/K_LUA/K_PASTE_START aren't normally received by 1835// vim.on_key() callbacks, so discard them along with the current key. 1836if (c == K_COMMAND ) { 1837xfree (getcmdkeycmd (NUL ,NULL ,0 , false)); 1838 }else if (c == K_LUA ) { 1839map_execute_lua (false, true); 1840 }else if (c == K_PASTE_START ) { 1841paste_repeat (0 ); 1842 } 1843// Discard the current key. 1844c = K_IGNORE ; 1845 } 1846kvi_destroy (on_key_buf ); 1847kvi_init (on_key_buf ); 1848 1849// Need to process the character before we know it's safe to do something 1850// else. 1851if (c != K_IGNORE ) { 1852state_no_longer_safe ("key typed" ); 1853 } 1854 1855return c ; 1856} 1857 1858/// Like vgetc(), but never return a NUL when called recursively, get a key 1859/// directly from the user (ignoring typeahead). 1860int safe_vgetc (void ) 1861{ 1862int c = vgetc (); 1863if (c == NUL ) { 1864c = get_keystroke (NULL ); 1865 } 1866return c ; 1867} 1868 1869/// Like safe_vgetc(), but loop to handle K_IGNORE. 1870/// Also ignore scrollbar events. 1871int plain_vgetc (void ) 1872{ 1873int c ; 1874 1875do { 1876c = safe_vgetc (); 1877 }while (c == K_IGNORE 1878|| c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR 1879|| c == K_MOUSEMOVE ); 1880return c ; 1881} 1882 1883/// Check if a character is available, such that vgetc() will not block. 1884/// If the next character is a special character or multi-byte, the returned 1885/// character is not valid!. 1886/// Returns NUL if no character is available. 1887int vpeekc (void ) 1888{ 1889if (can_get_ungot ()) { 1890return ungot .c ; 1891 } 1892return vgetorpeek (false); 1893} 1894 1895/// Check if any character is available, also half an escape sequence. 1896/// Trick: when no typeahead found, but there is something in the typeahead 1897/// buffer, it must be an ESC that is recognized as the start of a key code. 1898int vpeekc_any (void ) 1899{ 1900int c = vpeekc (); 1901if (c == NUL && typebuf .tb_len > 0 ) { 1902c = ESC ; 1903 } 1904return c ; 1905} 1906 1907/// Call vpeekc() without causing anything to be mapped. 1908/// @return true if a character is available, false otherwise. 1909bool char_avail (void ) 1910{ 1911if (test_disable_char_avail ) { 1912return false; 1913 } 1914no_mapping ++ ; 1915int retval = vpeekc (); 1916no_mapping -- ; 1917return retval != NUL ; 1918} 1919 1920static int no_reduce_keys = 0 ;///< Do not apply modifiers to the key. 1921 1922/// "getchar()" and "getcharstr()" functions 1923static void getchar_common (typval_T * argvars ,typval_T * rettv ,bool allow_number ) 1924FUNC_ATTR_NONNULL_ALL 1925{ 1926varnumber_T n = 0 ; 1927const int called_emsg_start = called_emsg ; 1928bool error = false; 1929bool simplify = true; 1930char cursor_flag = NUL ; 1931 1932if (argvars [0 ].v_type != VAR_UNKNOWN 1933&& tv_check_for_opt_dict_arg (argvars ,1 )== FAIL ) { 1934return ; 1935 } 1936 1937if (argvars [0 ].v_type != VAR_UNKNOWN && argvars [1 ].v_type == VAR_DICT ) { 1938dict_T * d = argvars [1 ].vval .v_dict ; 1939 1940if (allow_number ) { 1941allow_number = tv_dict_get_bool (d ,"number" , true); 1942 }else if (tv_dict_has_key (d ,"number" )) { 1943semsg (_ (e_invarg2 ),"number" ); 1944 } 1945 1946simplify = tv_dict_get_bool (d ,"simplify" , true); 1947 1948const char * cursor_str = tv_dict_get_string (d ,"cursor" , false); 1949if (cursor_str != NULL ) { 1950if (strcmp (cursor_str ,"hide" )!= 0 1951&& strcmp (cursor_str ,"keep" )!= 0 1952&& strcmp (cursor_str ,"msg" )!= 0 ) { 1953semsg (_ (e_invargNval ),"cursor" ,cursor_str ); 1954 }else { 1955cursor_flag = cursor_str [0 ]; 1956 } 1957 } 1958 } 1959 1960if (called_emsg != called_emsg_start ) { 1961return ; 1962 } 1963 1964if (cursor_flag == 'h' ) { 1965ui_busy_start (); 1966 } 1967 1968no_mapping ++ ; 1969allow_keys ++ ; 1970getchar_depth ++ ; 1971if (!simplify ) { 1972no_reduce_keys ++ ; 1973 } 1974atom_payload_start (); 1975while (true) { 1976if (cursor_flag == 'm' || (cursor_flag == NUL && msg_col > 0 )) { 1977ui_cursor_goto (msg_row ,msg_col ); 1978 } 1979 1980if (argvars [0 ].v_type == VAR_UNKNOWN 1981|| (argvars [0 ].v_type == VAR_NUMBER && argvars [0 ].vval .v_number == -1 )) { 1982// getchar(): blocking wait. 1983// TODO(bfredl): deduplicate shared logic with state_enter ? 1984if (!char_avail ()) { 1985// Flush screen updates before blocking. 1986ui_flush (); 1987input_get (NULL ,0 ,-1 ,typebuf .tb_change_cnt ,main_loop .events ); 1988if (!input_available ()&& !multiqueue_empty (main_loop .events )) { 1989state_handle_k_event (); 1990continue ; 1991 } 1992 } 1993n = safe_vgetc (); 1994 }else if (tv_get_bool_chk (& argvars [0 ],& error )) { 1995// getchar(1): only check if char avail 1996n = vpeekc_any (); 1997 }else if (error || vpeekc_any ()== NUL ) { 1998// illegal argument or getchar(0) and no char avail: return zero 1999n = 0 ; 2000 }else { 2001// getchar(0) and char avail() != NUL: get a character. 2002// Note that vpeekc_any() returns K_SPECIAL for K_IGNORE. 2003n = safe_vgetc (); 2004 } 2005 2006if (n == K_IGNORE 2007|| n == K_MOUSEMOVE 2008|| n == K_VER_SCROLLBAR 2009|| n == K_HOR_SCROLLBAR ) { 2010continue ; 2011 } 2012break ; 2013 } 2014atom_payload_end (); 2015no_mapping -- ; 2016allow_keys -- ; 2017getchar_depth -- ; 2018if (!simplify ) { 2019no_reduce_keys -- ; 2020 } 2021 2022if (cursor_flag == 'h' ) { 2023ui_busy_stop (); 2024 } 2025 2026set_vim_var_nr (VV_MOUSE_WIN ,0 ); 2027set_vim_var_nr (VV_MOUSE_WINID ,0 ); 2028set_vim_var_nr (VV_MOUSE_LNUM ,0 ); 2029set_vim_var_nr (VV_MOUSE_COL ,0 ); 2030 2031if (n != 0 && (!allow_number || IS_SPECIAL (n )|| mod_mask != 0 )) { 2032char temp [10 ];// modifier: 3, mbyte-char: 6, NUL: 1 2033int i = 0 ; 2034 2035// Turn a special key into three bytes, plus modifier. 2036if (mod_mask != 0 ) { 2037temp [i ++ ]= (char )K_SPECIAL ; 2038temp [i ++ ]= (char )KS_MODIFIER ; 2039temp [i ++ ]= (char )mod_mask ; 2040 } 2041if (IS_SPECIAL (n )) { 2042temp [i ++ ]= (char )K_SPECIAL ; 2043temp [i ++ ]= (char )K_SECOND (n ); 2044temp [i ++ ]= (char )K_THIRD (n ); 2045 }else { 2046i += utf_char2bytes ((int )n ,temp + i ); 2047 } 2048assert (i < 10 ); 2049temp [i ]= NUL ; 2050rettv -> v_type = VAR_STRING ; 2051rettv -> vval .v_string = xmemdupz (temp , (size_t )i ); 2052 2053if (is_mouse_key ((int )n )) { 2054int row = mouse_row ; 2055int col = mouse_col ; 2056int grid = mouse_grid ; 2057linenr_T lnum ; 2058win_T * wp ; 2059 2060if (row >=0 && col >=0 ) { 2061int winnr = 1 ; 2062// Find the window at the mouse coordinates and compute the 2063// text position. 2064win_T * const win = mouse_find_win_inner (& grid ,& row ,& col ); 2065if (win == NULL ) { 2066return ; 2067 } 2068mouse_comp_pos (win ,& row ,& col ,& lnum ); 2069for (wp = firstwin ;wp != win ;wp = wp -> w_next ) { 2070winnr ++ ; 2071 } 2072set_vim_var_nr (VV_MOUSE_WIN ,winnr ); 2073set_vim_var_nr (VV_MOUSE_WINID ,wp -> handle ); 2074set_vim_var_nr (VV_MOUSE_LNUM ,lnum ); 2075set_vim_var_nr (VV_MOUSE_COL ,col + 1 ); 2076 } 2077 } 2078 }else if (!allow_number ) { 2079rettv -> v_type = VAR_STRING ; 2080 }else { 2081rettv -> vval .v_number = n ; 2082 } 2083} 2084 2085/// "getchar()" function 2086void f_getchar (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2087{ 2088getchar_common (argvars ,rettv , true); 2089} 2090 2091/// "getcharstr()" function 2092void f_getcharstr (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2093{ 2094getchar_common (argvars ,rettv , false); 2095} 2096 2097/// "getcharmod()" function 2098void f_getcharmod (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2099{ 2100rettv -> vval .v_number = mod_mask ; 2101} 2102 2103typedef enum { 2104map_result_fail ,// failed (recursion limit, OOM), break loop 2105map_result_get ,// get a character from typeahead 2106map_result_retry ,// try to map again 2107map_result_nomatch ,// no matching mapping, get char 2108}map_result_T ; 2109 2110/// Put "string[new_slen]" in typebuf. 2111/// Remove "slen" bytes. 2112/// @return FAIL for error, OK otherwise. 2113static int put_string_in_typebuf (int offset ,int slen ,uint8_t * string ,int new_slen ) 2114FUNC_ATTR_NONNULL_ALL 2115{ 2116int extra = new_slen - slen ; 2117string [new_slen ]= NUL ; 2118if (extra < 0 ) { 2119// remove matched chars, taking care of noremap 2120del_typebuf (- extra ,offset ); 2121 }else if (extra > 0 ) { 2122// insert the extra space we need 2123if (ins_typebuf ((char * )string + slen ,REMAP_YES ,offset , false, false)== FAIL ) { 2124return FAIL ; 2125 } 2126 } 2127// Careful: del_typebuf() and ins_typebuf() may have reallocated 2128// typebuf.tb_buf[]! 2129memmove (typebuf .tb_buf + typebuf .tb_off + offset ,string , (size_t )new_slen ); 2130return OK ; 2131} 2132 2133/// Check if the bytes at the start of the typeahead buffer are a character used 2134/// in Insert mode completion. This includes the form with a CTRL modifier. 2135/// During completion started by complete() keys are mapped as usual. 2136static bool at_ins_compl_key (void ) 2137{ 2138uint8_t * p = typebuf .tb_buf + typebuf .tb_off ; 2139int c = * p ; 2140 2141if (typebuf .tb_len > 3 && c == K_SPECIAL && p [1 ]== KS_MODIFIER && (p [2 ]& MOD_MASK_CTRL )) { 2142c = p [3 ]& 0x1f ; 2143 } 2144return !ctrl_x_mode_eval () 2145&& ((ctrl_x_mode_not_default ()&& vim_is_ctrl_x_key (c )) 2146|| (compl_status_local ()&& (c == Ctrl_N || c == Ctrl_P ))); 2147} 2148 2149/// Check if typebuf.tb_buf[] contains a modifier plus key that can be changed 2150/// into just a key, apply that. 2151/// Check from typebuf.tb_buf[typebuf.tb_off] to typebuf.tb_buf[typebuf.tb_off + "max_offset"]. 2152/// @return the length of the replaced bytes, 0 if nothing changed, -1 for error. 2153static int check_simplify_modifier (int max_offset ) 2154{ 2155// We want full modifiers in Terminal mode so that the key can be correctly 2156// encoded 2157if ((State & MODE_TERMINAL )|| no_reduce_keys > 0 ) { 2158return 0 ; 2159 } 2160 2161for (int offset = 0 ;offset < max_offset ;offset ++ ) { 2162if (offset + 3 >=typebuf .tb_len ) { 2163break ; 2164 } 2165uint8_t * tp = typebuf .tb_buf + typebuf .tb_off + offset ; 2166if (tp [0 ]== K_SPECIAL && tp [1 ]== KS_MODIFIER ) { 2167// A modifier was not used for a mapping, apply it to ASCII 2168// keys. Shift would already have been applied. 2169int modifier = tp [2 ]; 2170int c = tp [3 ]; 2171int new_c = merge_modifiers (c ,& modifier ); 2172 2173if (new_c != c ) { 2174if (offset == 0 ) { 2175// At the start: remember the character and mod_mask before 2176// merging, in some cases, e.g. at the hit-return prompt, 2177// they are put back in the typeahead buffer. 2178vgetc_char = c ; 2179vgetc_mod_mask = tp [2 ]; 2180 } 2181uint8_t new_string [MB_MAXBYTES ]; 2182int len ; 2183if (IS_SPECIAL (new_c )) { 2184new_string [0 ]= K_SPECIAL ; 2185new_string [1 ]= (uint8_t )K_SECOND (new_c ); 2186new_string [2 ]= (uint8_t )K_THIRD (new_c ); 2187len = 3 ; 2188 }else { 2189len = utf_char2bytes (new_c , (char * )new_string ); 2190 } 2191if (modifier == 0 ) { 2192if (put_string_in_typebuf (offset ,4 ,new_string ,len )== FAIL ) { 2193return -1 ; 2194 } 2195 }else { 2196tp [2 ]= (uint8_t )modifier ; 2197if (put_string_in_typebuf (offset + 3 ,1 ,new_string ,len )== FAIL ) { 2198return -1 ; 2199 } 2200 } 2201return len ; 2202 } 2203 } 2204 } 2205return 0 ; 2206} 2207 2208/// Returns the next character from a NUL-terminated UTF-8-encoded escaped-K_SPECIAL string. 2209/// 2210/// Combining characters are treated as separate code points. 2211/// 2212/// @param[inout] itp Pointer to the input string pointer. The string pointer will be advanced to 2213/// the next character. 2214/// @param nomap If non-zero, then multi-byte characters are not decoded and the function 2215/// always returns the next byte from the string. 2216/// @return Unicode code point or 0, if at the end. 2217/// - Returns 0 when NUL is in the middle of a multi-byte sequence. This allows 2218/// calling code to request more data. 2219/// - If decoding of a multi-byte character fails, returns the first byte of 2220/// the encoded character. 2221static int char_iter (const uint8_t ** itp ,int nomap ) 2222FUNC_ATTR_NONNULL_ALL 2223{ 2224const uint8_t * it = * itp ; 2225int c = * it ; 2226if (c == NUL ) { 2227return 0 ; 2228 } 2229 2230if (nomap == 0 ) { 2231int mblen = MB_BYTE2LEN (c ); 2232if (mblen > 1 ) { 2233uint8_t buf [MB_MAXBYTES + 1 ]; 2234buf [0 ]= (uint8_t )c ; 2235int i = 1 ; 2236 2237do { 2238buf [i ]= *++ it ; 2239if (buf [i ]== K_SPECIAL ) { 2240// Follows vgetc()'s logic: Must be a K_SPECIAL - KS_SPECIAL - KE_FILLER sequence, which 2241// represents a K_SPECIAL (0x80). Skip KS_SPECIAL and KE_FILLER. 2242if (*++ it == NUL || *++ it == NUL ) { 2243break ; 2244 } 2245 } 2246 }while (buf [i ]!= NUL && ++ i < mblen ); 2247 2248if (i != mblen ) { 2249* itp = it ; 2250return 0 ; 2251 } 2252 2253c = utf_ptr2char ((const char * )buf ); 2254if (c == buf [0 ]) { 2255// Invalid UTF-8 sequence 2256it = * itp ; 2257 } 2258 } 2259 } 2260 2261* itp = ++ it ; 2262return c ; 2263} 2264 2265/// Handle mappings in the typeahead buffer. 2266/// - When something was mapped, return map_result_retry for recursive mappings. 2267/// - When nothing mapped and typeahead has a character: return map_result_get. 2268/// - When there is no match yet, return map_result_nomatch, need to get more 2269/// typeahead. 2270/// - On failure (out of memory) return map_result_fail. 2271static int handle_mapping (int * keylenp ,const bool * timedout ,int * mapdepth ,bool advance ) 2272FUNC_ATTR_NONNULL_ARG (1 ) 2273{ 2274mapblock_T * mp = NULL ; 2275mapblock_T * mp2 ; 2276mapblock_T * mp_match ; 2277int mp_match_len = 0 ; 2278int tb_match_len = 0 ; 2279int max_mlen = 0 ; 2280int keylen = * keylenp ; 2281int local_State = get_real_state (); 2282bool is_plug_map = false; 2283 2284// If typeahead starts with <Plug> then remap, even for a "noremap" mapping. 2285if (typebuf .tb_len >=3 2286&& typebuf .tb_buf [typebuf .tb_off ]== K_SPECIAL 2287&& typebuf .tb_buf [typebuf .tb_off + 1 ]== KS_EXTRA 2288&& typebuf .tb_buf [typebuf .tb_off + 2 ]== KE_PLUG ) { 2289is_plug_map = true; 2290 } 2291 2292// Check for a mappable key sequence. 2293// Walk through one maphash[] list until we find an entry that matches. 2294// 2295// Don't look for mappings if: 2296// - no_mapping set: mapping disabled (e.g. for CTRL-V) 2297// - maphash_valid not set: no mappings present. 2298// - typebuf.tb_buf[typebuf.tb_off] should not be remapped 2299// - in insert or cmdline mode and 'paste' option set 2300// - waiting for "hit return to continue" and CR or SPACE typed 2301// - waiting for a char with --more-- 2302// - in Ctrl-X mode, and we get a valid char for that mode 2303// - in Ctrl-X mode (not started by complete()), and we get a valid char for that mode 2304int tb_b1 = typebuf .tb_buf [typebuf .tb_off ]; 2305if (no_mapping == 0 2306&& (no_zero_mapping == 0 || tb_b1 != '0' ) 2307&& (typebuf .tb_maplen == 0 || is_plug_map 2308|| (!(typebuf .tb_noremap [typebuf .tb_off ]& (RM_NONE |RM_ABBR )))) 2309&& !(p_paste && (State & (MODE_INSERT |MODE_CMDLINE ))) 2310&& !(State == MODE_HITRETURN && (tb_b1 == CAR || tb_b1 == ' ' )) 2311&& State != MODE_ASKMORE 2312&& !at_ins_compl_key ()) { 2313int nolmaplen ; 2314int tb_c1 = tb_b1 ; 2315const uint8_t * tb_iter = typebuf .tb_buf + typebuf .tb_off ; 2316 2317if (tb_b1 == K_SPECIAL ) { 2318nolmaplen = 2 ; 2319tb_iter += 1 ; 2320 }else { 2321tb_c1 = char_iter (& tb_iter ,0 ); 2322if (tb_c1 == 0 ) { 2323if (* timedout ) { 2324* keylenp = 0 ; 2325return map_result_get ; 2326 } 2327* keylenp = KEYLEN_PART_KEY ; 2328return map_result_nomatch ; 2329 } 2330 2331int orig_tb_c1 = tb_c1 ; 2332LANGMAP_ADJUST (tb_c1 , ((State & (MODE_CMDLINE |MODE_INSERT ))== 0 2333&& get_real_state ()!= MODE_SELECT )); 2334if (orig_tb_c1 != tb_c1 ) { 2335// Mapped by 'langmap', update the first byte 2336char cbuf [6 ]; 2337utf_char2bytes (tb_c1 ,cbuf ); 2338tb_b1 = (uint8_t )cbuf [0 ]; 2339 } 2340nolmaplen = 0 ; 2341 } 2342// First try buffer-local mappings. 2343mp = get_buf_maphash_list (local_State ,tb_b1 ); 2344mp2 = get_maphash_list (local_State ,tb_b1 ); 2345if (mp == NULL ) { 2346// There are no buffer-local mappings. 2347mp = mp2 ; 2348mp2 = NULL ; 2349 } 2350// Loop until a partly matching mapping is found or all (local) 2351// mappings have been checked. 2352// The longest full match is remembered in "mp_match". 2353// A full match is only accepted if there is no partly match, so "aa" 2354// and "aaa" can both be mapped. 2355mp_match = NULL ; 2356mp_match_len = 0 ; 2357tb_match_len = 0 ; 2358for (;mp != NULL ;mp -> m_next == NULL ? (mp = mp2 ,mp2 = NULL ) : (mp = mp -> m_next )) { 2359// Only consider an entry if the first character matches and it is 2360// for the current state. 2361// Skip ":lmap" mappings if keys were mapped. 2362const uint8_t * key_iter = (const uint8_t * )mp -> m_keys ; 2363 2364if (char_iter (& key_iter ,0 )== tb_c1 && (mp -> m_mode & local_State ) 2365&& ((mp -> m_mode & MODE_LANGMAP )== 0 || typebuf .tb_maplen == 0 )) { 2366int nomap = nolmaplen ; 2367int modifiers = 0 ; 2368int c2 ; 2369const uint8_t * tmp_tb_iter = tb_iter ; 2370// Match length in key buffer 2371int mlen = (int )(key_iter - (const uint8_t * )mp -> m_keys ); 2372// Match length in typeahead buffer 2373int tb_mlen = (int )(tmp_tb_iter - typebuf .tb_buf )- typebuf .tb_off ; 2374 2375// find the match length of this mapping 2376while ((c2 = char_iter (& tmp_tb_iter ,nomap ))!= 0 ) { 2377int tb_nomap = nomap ; 2378if (nomap > 0 ) { 2379if (nomap == 2 && c2 == KS_MODIFIER ) { 2380modifiers = 1 ; 2381 }else if (nomap == 1 && modifiers == 1 ) { 2382modifiers = c2 ; 2383 } 2384nomap -- ; 2385 }else { 2386if (c2 == K_SPECIAL ) { 2387nomap = 2 ; 2388 }else if (merge_modifiers (c2 ,& modifiers )== c2 ) { 2389// Only apply 'langmap' if merging modifiers into 2390// the key will not result in another character, 2391// so that 'langmap' behaves consistently in 2392// different terminals and GUIs. 2393LANGMAP_ADJUST (c2 , true); 2394 } 2395modifiers = 0 ; 2396 } 2397 2398int key_char = char_iter (& key_iter ,tb_nomap ); 2399if (key_char != c2 ) { 2400break ; 2401 } 2402 2403mlen = (int )(key_iter - (const uint8_t * )mp -> m_keys ); 2404tb_mlen = (int )(tmp_tb_iter - typebuf .tb_buf )- typebuf .tb_off ; 2405 } 2406 2407// Check an entry whether it matches. 2408// - Full match: mlen == keylen 2409// - Partly match: mlen == typebuf.tb_len 2410keylen = mp -> m_keylen ; 2411if (mlen == keylen || (mlen == typebuf .tb_len && typebuf .tb_len < keylen )) { 2412int n ; 2413 2414// If only script-local mappings are allowed, check if the 2415// mapping starts with K_SNR. 2416uint8_t * s = typebuf .tb_noremap + typebuf .tb_off ; 2417if (* s == RM_SCRIPT 2418&& ((uint8_t )mp -> m_keys [0 ]!= K_SPECIAL 2419|| (uint8_t )mp -> m_keys [1 ]!= KS_EXTRA 2420|| mp -> m_keys [2 ]!= KE_SNR )) { 2421continue ; 2422 } 2423 2424// If one of the typed keys cannot be remapped, skip the entry. 2425for (n = mlen ;-- n >=0 ;) { 2426if (* s ++ & (RM_NONE |RM_ABBR )) { 2427break ; 2428 } 2429 } 2430if (!is_plug_map && n >=0 ) { 2431continue ; 2432 } 2433 2434if (keylen > typebuf .tb_len ) { 2435if (!* timedout && !(mp_match != NULL && mp_match -> m_nowait )) { 2436// break at a partly match 2437keylen = KEYLEN_PART_MAP ; 2438break ; 2439 } 2440 }else if (keylen > mp_match_len 2441|| (keylen == mp_match_len 2442&& mp_match != NULL 2443&& (mp_match -> m_mode & MODE_LANGMAP )== 0 2444&& (mp -> m_mode & MODE_LANGMAP )!= 0 )) { 2445// found a longer match 2446mp_match = mp ; 2447mp_match_len = keylen ; 2448tb_match_len = tb_mlen ; 2449 } 2450 }else { 2451// No match; may have to check for termcode at next character. 2452max_mlen = MAX (max_mlen ,mlen ); 2453 } 2454 } 2455 } 2456 2457// If no partly match found, use the longest full match. 2458if (keylen != KEYLEN_PART_MAP && mp_match != NULL ) { 2459mp = mp_match ; 2460keylen = tb_match_len ; 2461 } 2462 } 2463 2464if ((mp == NULL || max_mlen > mp_match_len )&& keylen != KEYLEN_PART_MAP ) { 2465// When no matching mapping found or found a non-matching mapping that 2466// matches at least what the matching mapping matched: 2467// Try to include the modifier into the key when mapping is allowed. 2468if (no_mapping == 0 || allow_keys != 0 ) { 2469if (tb_b1 == K_SPECIAL 2470&& (typebuf .tb_len < 2 2471|| (typebuf .tb_buf [typebuf .tb_off + 1 ]== KS_MODIFIER && typebuf .tb_len < 4 ))) { 2472// Incomplete modifier sequence: cannot decide whether to simplify yet. 2473keylen = KEYLEN_PART_KEY ; 2474 }else { 2475// Try to include the modifier into the key. 2476keylen = check_simplify_modifier (max_mlen + 1 ); 2477if (keylen < 0 ) { 2478// ins_typebuf() failed 2479return map_result_fail ; 2480 } 2481 } 2482 }else { 2483keylen = 0 ; 2484 } 2485if (keylen == 0 ) {// no simplification has been done 2486// If there was no mapping at all use the character from the 2487// typeahead buffer right here. 2488if (mp == NULL ) { 2489* keylenp = keylen ; 2490return map_result_get ;// get character from typeahead 2491 } 2492 } 2493 2494if (keylen > 0 ) {// keys have been simplified 2495* keylenp = keylen ; 2496return map_result_retry ;// try mapping again 2497 } 2498 2499if (keylen < 0 ) { 2500// Incomplete key sequence: get some more characters. 2501assert (keylen == KEYLEN_PART_KEY ); 2502 }else { 2503assert (mp != NULL ); 2504// When a matching mapping was found use that one. 2505keylen = tb_match_len ; 2506 } 2507 } 2508 2509// complete match 2510if (keylen >=0 && keylen <=typebuf .tb_len ) { 2511int i ; 2512char * map_str = NULL ; 2513 2514// Write chars to script file(s). 2515// Note: :lmap mappings are written *after* being applied. #5658 2516if (keylen > typebuf .tb_maplen && (mp -> m_mode & MODE_LANGMAP )== 0 ) { 2517gotchars (typebuf .tb_buf + typebuf .tb_off + typebuf .tb_maplen , 2518 (size_t )(keylen - typebuf .tb_maplen )); 2519// A typed key sequence resolved this mapping (not a nested expansion: 2520// those keys come from another mapping): open its composite. 2521atom_map_start (mp -> m_keys , (size_t )mp -> m_keylen , !advance ); 2522 } 2523 2524cmd_silent = (typebuf .tb_silent > 0 ); 2525del_typebuf (keylen ,0 );// remove the mapped keys 2526 2527// Put the replacement string in front of mapstr. 2528// The depth check catches ":map x y" and ":map y x". 2529if (++* mapdepth >=p_mmd ) { 2530emsg (_ (e_recursive_mapping )); 2531if (State & MODE_CMDLINE ) { 2532redrawcmdline (); 2533 }else { 2534setcursor (); 2535 } 2536flush_buffers (FLUSH_MINIMAL ); 2537* mapdepth = 0 ;// for next one 2538* keylenp = keylen ; 2539return map_result_fail ; 2540 } 2541 2542// In Select mode and a Visual mode mapping is used: Switch to Visual 2543// mode temporarily. Append K_SELECT to switch back to Select mode. 2544if (Visual .active && Visual .select && (mp -> m_mode & MODE_VISUAL )) { 2545Visual .select = false; 2546ins_typebuf (K_SELECT_STRING ,REMAP_NONE ,0 , true, false); 2547 } 2548 2549// Copy the values from *mp that are used, because evaluating the 2550// expression may invoke a function that redefines the mapping, thereby 2551// making *mp invalid. 2552const bool save_m_expr = mp -> m_expr ; 2553const int save_m_noremap = mp -> m_noremap ; 2554const bool save_m_silent = mp -> m_silent ; 2555char * save_m_keys = NULL ;// only saved when needed 2556char * save_alt_m_keys = NULL ;// only saved when needed 2557const int save_alt_m_keylen = mp -> m_alt != NULL ?mp -> m_alt -> m_keylen :0 ; 2558 2559// Handle ":map <expr>": evaluate the {rhs} as an 2560// expression. Also save and restore the command line 2561// for "normal :". 2562if (mp -> m_expr ) { 2563const int save_vgetc_busy = vgetc_busy ; 2564const bool save_may_garbage_collect = may_garbage_collect ; 2565const int prev_did_emsg = did_emsg ; 2566 2567vgetc_busy = 0 ; 2568may_garbage_collect = false; 2569 2570save_m_keys = xmemdupz (mp -> m_keys , (size_t )mp -> m_keylen ); 2571save_alt_m_keys = mp -> m_alt != NULL 2572 ?xmemdupz (mp -> m_alt -> m_keys , (size_t )save_alt_m_keylen ) 2573 :NULL ; 2574map_str = eval_map_expr (mp ,NUL ); 2575 2576if ((map_str == NULL || * map_str == NUL )) { 2577// If an error was displayed and the expression returns an empty 2578// string, generate a <Nop> to allow for a redraw. 2579if (prev_did_emsg != did_emsg ) { 2580char buf [4 ]; 2581xfree (map_str ); 2582buf [0 ]= (char )K_SPECIAL ; 2583buf [1 ]= (char )KS_EXTRA ; 2584buf [2 ]= KE_IGNORE ; 2585buf [3 ]= NUL ; 2586map_str = xmemdupz (buf ,3 ); 2587if (State & MODE_CMDLINE ) { 2588// redraw the command below the error 2589msg_didout = true; 2590msg_row = MAX (msg_row ,cmdline_row ); 2591redrawcmd (); 2592 } 2593 }else if (State & (MODE_NORMAL |MODE_INSERT )) { 2594// otherwise, just put back the cursor 2595setcursor (); 2596 } 2597 } 2598 2599vgetc_busy = save_vgetc_busy ; 2600may_garbage_collect = save_may_garbage_collect ; 2601 }else { 2602map_str = mp -> m_str ; 2603 } 2604 2605// Insert the 'to' part in the typebuf.tb_buf. 2606// If 'from' field is the same as the start of the 'to' field, don't 2607// remap the first character (but do allow abbreviations). 2608// If m_noremap is set, don't remap the whole 'to' part. 2609if (map_str == NULL ) { 2610i = FAIL ; 2611 }else { 2612int noremap ; 2613 2614// If this is a LANGMAP mapping, then we didn't record the keys 2615// at the start of the function and have to record them now. 2616if (keylen > typebuf .tb_maplen && (mp -> m_mode & MODE_LANGMAP )!= 0 ) { 2617gotchars ((uint8_t * )map_str ,strlen (map_str )); 2618 } 2619 2620if (save_m_noremap != REMAP_YES ) { 2621noremap = save_m_noremap ; 2622 }else if (save_m_expr 2623 ?strncmp (map_str ,save_m_keys , (size_t )keylen )== 0 2624|| (save_alt_m_keys != NULL 2625&& strncmp (map_str ,save_alt_m_keys , 2626 (size_t )save_alt_m_keylen )== 0 ) 2627 :strncmp (map_str ,mp -> m_keys , (size_t )keylen )== 0 2628|| (mp -> m_alt != NULL 2629&& strncmp (map_str ,mp -> m_alt -> m_keys , 2630 (size_t )mp -> m_alt -> m_keylen )== 0 )) { 2631noremap = REMAP_SKIP ; 2632 }else { 2633noremap = REMAP_YES ; 2634 } 2635i = ins_typebuf (map_str ,noremap ,0 , true,cmd_silent || save_m_silent ); 2636if (save_m_expr ) { 2637xfree (map_str ); 2638 } 2639 } 2640xfree (save_m_keys ); 2641xfree (save_alt_m_keys ); 2642* keylenp = keylen ; 2643if (i == FAIL ) { 2644return map_result_fail ; 2645 } 2646return map_result_retry ; 2647 } 2648 2649* keylenp = keylen ; 2650return map_result_nomatch ; 2651} 2652 2653/// unget one character (can only be done once!) 2654/// If the character was stuffed, vgetc() will get it next time it is called. 2655/// Otherwise vgetc() will only get it when the stuff buffer is empty. 2656void vungetc (int c ) 2657{ 2658ungot = (UngotKey ){ 2659 .c = c , 2660 .mod_mask = mod_mask , 2661 .mouse_grid = mouse_grid , 2662 .mouse_row = mouse_row , 2663 .mouse_col = mouse_col , 2664 .stuffed = KeyStuffed , 2665 }; 2666} 2667 2668/// When peeking and not getting a character, reg_executing cannot be cleared 2669/// yet, so set a flag to clear it later. 2670void check_end_reg_executing (bool advance ) 2671{ 2672if (reg_executing != 0 && (typebuf .tb_maplen == 0 || pending_end_reg_executing )) { 2673if (advance ) { 2674reg_executing = 0 ; 2675pending_end_reg_executing = false; 2676 }else { 2677pending_end_reg_executing = true; 2678 } 2679 } 2680} 2681 2682/// Gets a byte: 2683/// 1. from the stuffbuffer 2684/// This is used for abbreviated commands like "D" -> "d$". 2685/// Also used to redo a command for ".". 2686/// 2. from the typeahead buffer 2687/// Stores text obtained previously but not used yet. 2688/// Also stores the result of mappings. 2689/// Also used for the ":normal" command. 2690/// 3. from the user 2691/// This may do a blocking wait if "advance" is true. 2692/// 2693/// if "advance" is true (vgetc()): 2694/// Really get the character. 2695/// KeyTyped is set to true in the case the user typed the key. 2696/// KeyStuffed is true if the character comes from the stuff buffer. 2697/// if "advance" is false (vpeekc()): 2698/// Just look whether there is a character available. 2699/// Return NUL if not. 2700/// 2701/// When `no_mapping` (global) is zero, checks for mappings in the current mode. 2702/// Only returns one byte (of a multi-byte character). 2703/// K_SPECIAL may be escaped, need to get two more bytes then. 2704static int vgetorpeek (bool advance ) 2705{ 2706int c ; 2707bool timedout = false;// waited for more than 'timeoutlen' 2708// for mapping to complete or 2709// 'ttimeoutlen' for complete key code 2710int mapdepth = 0 ;// check for recursive mapping 2711bool mode_deleted = false;// set when mode has been deleted 2712 2713// This function doesn't work very well when called recursively. This may 2714// happen though, because of: 2715// 1. The call to add_to_showcmd(). char_avail() is then used to check if 2716// there is a character available, which calls this function. In that 2717// case we must return NUL, to indicate no character is available. 2718// 2. A GUI callback function writes to the screen, causing a 2719// wait_return(). 2720// Using ":normal" can also do this, but it saves the typeahead buffer, 2721// thus it should be OK. But don't get a key from the user then. 2722if (vgetc_busy > 0 && ex_normal_busy == 0 ) { 2723return NUL ; 2724 } 2725 2726vgetc_busy ++ ; 2727 2728if (advance ) { 2729KeyStuffed = false; 2730typebuf_was_empty = false; 2731 } 2732 2733init_typebuf (); 2734start_stuff (); 2735check_end_reg_executing (advance ); 2736do { 2737// get a character: 1. from the stuffbuffer 2738if (typeahead_char != 0 ) { 2739c = typeahead_char ; 2740if (advance ) { 2741typeahead_char = 0 ; 2742 } 2743 }else { 2744c = read_readbuffers (advance ); 2745 } 2746if (c != NUL && !got_int ) { 2747if (advance ) { 2748// KeyTyped = false; When the command that stuffed something 2749// was typed, behave like the stuffed command was typed. 2750// needed for CTRL-W CTRL-] to open a fold, for example. 2751KeyStuffed = true; 2752 } 2753if (typebuf .tb_no_abbr_cnt == 0 ) { 2754typebuf .tb_no_abbr_cnt = 1 ;// no abbreviations now 2755 } 2756 }else { 2757// Loop until we either find a matching mapped key, or we 2758// are sure that it is not a mapped key. 2759// If a mapped key sequence is found we go back to the start to 2760// try re-mapping. 2761while (true) { 2762check_end_reg_executing (advance ); 2763// os_breakcheck() is slow, don't use it too often when 2764// inside a mapping. But call it each time for typed 2765// characters. 2766if (typebuf .tb_maplen ) { 2767line_breakcheck (); 2768 }else { 2769// os_breakcheck() can call input_enqueue() 2770if ((mapped_ctrl_c |curbuf -> b_mapped_ctrl_c )& get_real_state ()) { 2771ctrl_c_interrupts = false; 2772 } 2773os_breakcheck ();// check for CTRL-C 2774ctrl_c_interrupts = true; 2775 } 2776int keylen = 0 ; 2777if (got_int ) { 2778// flush all input 2779c = inchar (typebuf .tb_buf ,typebuf .tb_buflen - 1 ,0 ); 2780 2781// If inchar() returns true (script file was active) or we 2782// are inside a mapping, get out of Insert mode. 2783// Otherwise we behave like having gotten a CTRL-C. 2784// As a result typing CTRL-C in insert mode will 2785// really insert a CTRL-C. 2786if ((c || typebuf .tb_maplen ) 2787&& (State & (MODE_INSERT |MODE_CMDLINE ))) { 2788c = ESC ; 2789 }else { 2790c = Ctrl_C ; 2791 } 2792flush_buffers (FLUSH_INPUT );// flush all typeahead 2793 2794if (advance ) { 2795// Also record this character, it might be needed to 2796// get out of Insert mode. 2797* typebuf .tb_buf = (uint8_t )c ; 2798gotchars (typebuf .tb_buf ,1 ); 2799 } 2800cmd_silent = false; 2801 2802break ; 2803 }else if (typebuf .tb_len > 0 ) { 2804// Check for a mapping in "typebuf". 2805map_result_T result = (map_result_T )handle_mapping (& keylen ,& timedout ,& mapdepth , 2806advance ); 2807 2808if (result == map_result_retry ) { 2809// try mapping again 2810continue ; 2811 } 2812 2813if (result == map_result_fail ) { 2814atom_composite_abort (); 2815// failed, use the outer loop 2816c = -1 ; 2817break ; 2818 } 2819 2820if (result == map_result_get ) { 2821// get a character: 2. from the typeahead buffer 2822c = typebuf .tb_buf [typebuf .tb_off ]; 2823if (advance ) {// remove chars from tb_buf 2824cmd_silent = (typebuf .tb_silent > 0 ); 2825if (typebuf .tb_maplen > 0 ) { 2826KeyTyped = false; 2827 }else { 2828KeyTyped = true; 2829// write char to script file(s) 2830gotchars (typebuf .tb_buf + typebuf .tb_off ,1 ); 2831 } 2832KeyNoremap = (unsigned char )typebuf .tb_noremap [typebuf .tb_off ]; 2833del_typebuf (1 ,0 ); 2834 } 2835break ;// got character, break the for loop 2836 } 2837 2838// not enough characters, get more 2839 } 2840 2841// get a character: 3. from the user - handle <Esc> in Insert mode 2842 2843// special case: if we get an <ESC> in insert mode and there 2844// are no more characters at once, we pretend to go out of 2845// insert mode. This prevents the one second delay after 2846// typing an <ESC>. If we get something after all, we may 2847// have to redisplay the mode. That the cursor is in the wrong 2848// place does not matter. 2849c = 0 ; 2850int new_wcol = curwin -> w_wcol ; 2851int new_wrow = curwin -> w_wrow ; 2852if (advance 2853&& typebuf .tb_len == 1 2854&& typebuf .tb_buf [typebuf .tb_off ]== ESC 2855&& !no_mapping 2856&& ex_normal_busy == 0 2857&& typebuf .tb_maplen == 0 2858&& (State & MODE_INSERT ) 2859&& (p_timeout || (keylen == KEYLEN_PART_KEY && p_ttimeout )) 2860&& (c = inchar (typebuf .tb_buf + typebuf .tb_off + typebuf .tb_len ,3 ,25 ))== 0 ) { 2861if (mode_displayed ) { 2862unshowmode (true); 2863mode_deleted = true; 2864 } 2865validate_cursor (curwin ); 2866int old_wcol = curwin -> w_wcol ; 2867int old_wrow = curwin -> w_wrow ; 2868 2869// move cursor left, if possible 2870if (curwin -> w_cursor .col != 0 ) { 2871colnr_T col = 0 ; 2872char * ptr ; 2873if (curwin -> w_wcol > 0 ) { 2874// After auto-indenting and no text is following, 2875// we are expecting to truncate the trailing 2876// white-space, so find the last non-white 2877// character -- webb 2878if (Ins .did_ai && * skipwhite (get_cursor_line_ptr ()+ curwin -> w_cursor .col )== NUL ) { 2879curwin -> w_wcol = 0 ; 2880ptr = get_cursor_line_ptr (); 2881char * endptr = ptr + curwin -> w_cursor .col ; 2882 2883CharsizeArg csarg ; 2884CSType cstype = init_charsize_arg (& csarg ,curwin ,curwin -> w_cursor .lnum ,ptr ); 2885StrCharInfo ci = utf_ptr2StrCharInfo (ptr ); 2886int vcol = 0 ; 2887while (ci .ptr < endptr ) { 2888if (!ascii_iswhite (ci .chr .value )) { 2889curwin -> w_wcol = vcol ; 2890 } 2891ClusterInfo cli = utf_ClusterInfo (ci ); 2892vcol += win_charsize (cstype ,vcol ,ci .ptr ,ci .chr .value ,& csarg ,cli .cells ).width ; 2893ci = cli .next ; 2894 } 2895 2896curwin -> w_wrow = curwin -> w_cline_row 2897+ curwin -> w_wcol /curwin -> w_view_width ; 2898curwin -> w_wcol %=curwin -> w_view_width ; 2899curwin -> w_wcol += win_col_off (curwin ); 2900col = 0 ;// no correction needed 2901 }else { 2902curwin -> w_wcol -- ; 2903col = curwin -> w_cursor .col - 1 ; 2904 } 2905 }else if (curwin -> w_p_wrap && curwin -> w_wrow ) { 2906curwin -> w_wrow -- ; 2907curwin -> w_wcol = curwin -> w_view_width - 1 ; 2908col = curwin -> w_cursor .col - 1 ; 2909 } 2910if (col > 0 && curwin -> w_wcol > 0 ) { 2911// Correct when the cursor is on the right halve 2912// of a double-wide character. 2913ptr = get_cursor_line_ptr (); 2914col -= utf_head_off (ptr ,ptr + col ); 2915if (utf_ptr2cells (ptr + col )> 1 ) { 2916curwin -> w_wcol -- ; 2917 } 2918 } 2919 } 2920setcursor (); 2921ui_flush (); 2922new_wcol = curwin -> w_wcol ; 2923new_wrow = curwin -> w_wrow ; 2924curwin -> w_wcol = old_wcol ; 2925curwin -> w_wrow = old_wrow ; 2926 } 2927if (c < 0 ) { 2928continue ;// end of input script reached 2929 } 2930 2931// Allow mapping for just typed characters. When we get here c 2932// is the number of extra bytes and typebuf.tb_len is 1. 2933for (int n = 1 ;n <=c ;n ++ ) { 2934typebuf .tb_noremap [typebuf .tb_off + n ]= RM_YES ; 2935 } 2936typebuf .tb_len += c ; 2937 2938// buffer full, don't map 2939if (typebuf .tb_len >=typebuf .tb_maplen + MAXMAPLEN ) { 2940timedout = true; 2941continue ; 2942 } 2943 2944if (ex_normal_busy > 0 ) { 2945static int tc = 0 ; 2946 2947// No typeahead left and inside ":normal". Must return 2948// something to avoid getting stuck. When an incomplete 2949// mapping is present, behave like it timed out. 2950if (typebuf .tb_len > 0 ) { 2951timedout = true; 2952continue ; 2953 } 2954 2955// For the command line only CTRL-C always breaks it. 2956// For the cmdline window: Alternate between ESC and 2957// CTRL-C: ESC for most situations and CTRL-C to close the 2958// cmdline window. 2959c = ((State & MODE_CMDLINE )|| (cmdwin_type > 0 && tc == ESC )) ?Ctrl_C :ESC ; 2960tc = c ; 2961 2962// set a flag to indicate this wasn't a normal char 2963if (advance ) { 2964typebuf_was_empty = true; 2965 } 2966 2967// no chars to block abbreviations for 2968typebuf .tb_no_abbr_cnt = 0 ; 2969 2970break ; 2971 } 2972 2973// get a character: 3. from the user - update display 2974 2975// In insert mode a screen update is skipped when characters 2976// are still available. But when those available characters 2977// are part of a mapping, and we are going to do a blocking 2978// wait here. Need to update the screen to display the 2979// changed text so far. Also for when 'lazyredraw' is set and 2980// redrawing was postponed because there was something in the 2981// input buffer (e.g., termresponse). 2982if (((State & MODE_INSERT )!= 0 || p_lz )&& (State & MODE_CMDLINE )== 0 2983&& advance && must_redraw != 0 && !need_wait_return ) { 2984update_screen (); 2985setcursor ();// put cursor back where it belongs 2986 } 2987 2988// If we have a partial match (and are going to wait for more 2989// input from the user), show the partially matched characters 2990// to the user with showcmd. 2991int showcmd_idx = 0 ; 2992bool showing_partial = false; 2993if (typebuf .tb_len > 0 && advance ) { 2994if (((State & (MODE_NORMAL |MODE_INSERT ))|| State == MODE_LANGMAP ) 2995&& State != MODE_HITRETURN ) { 2996// this looks nice when typing a dead character map 2997if (State & MODE_INSERT 2998&& ptr2cells ((char * )typebuf .tb_buf + typebuf .tb_off + typebuf .tb_len - 1 )== 1 ) { 2999edit_putchar (typebuf .tb_buf [typebuf .tb_off + typebuf .tb_len - 1 ], false); 3000setcursor ();// put cursor back where it belongs 3001showing_partial = true; 3002 } 3003// need to use the col and row from above here 3004int old_wcol = curwin -> w_wcol ; 3005int old_wrow = curwin -> w_wrow ; 3006curwin -> w_wcol = new_wcol ; 3007curwin -> w_wrow = new_wrow ; 3008push_showcmd (); 3009if (typebuf .tb_len > SHOWCMD_COLS ) { 3010showcmd_idx = typebuf .tb_len - SHOWCMD_COLS ; 3011 } 3012while (showcmd_idx < typebuf .tb_len ) { 3013add_byte_to_showcmd (typebuf .tb_buf [typebuf .tb_off + showcmd_idx ++ ]); 3014 } 3015curwin -> w_wcol = old_wcol ; 3016curwin -> w_wrow = old_wrow ; 3017 } 3018 3019// This looks nice when typing a dead character map. 3020// There is no actual command line for get_number(). 3021if ((State & MODE_CMDLINE ) 3022&& get_cmdline_info ()-> cmdbuff != NULL 3023&& cmdline_star == 0 ) { 3024char * p = (char * )typebuf .tb_buf + typebuf .tb_off + typebuf .tb_len - 1 ; 3025if (ptr2cells (p )== 1 && (uint8_t )(* p )< 128 ) { 3026putcmdline (* p , false); 3027showing_partial = true; 3028 } 3029 } 3030 } 3031 3032// get a character: 3. from the user - get it 3033if (typebuf .tb_len == 0 ) { 3034// timedout may have been set if a mapping with empty RHS 3035// fully matched while longer mappings timed out. 3036timedout = false; 3037 } 3038 3039int wait_time = 0 ; 3040 3041if (advance ) { 3042if (typebuf .tb_len == 0 || !(p_timeout || (p_ttimeout && keylen == KEYLEN_PART_KEY ))) { 3043// blocking wait 3044wait_time = -1 ; 3045 }else if (keylen == KEYLEN_PART_KEY && p_ttm >=0 ) { 3046wait_time = (int )p_ttm ; 3047 }else { 3048wait_time = (int )p_tm ; 3049 } 3050 } 3051 3052int wait_tb_len = typebuf .tb_len ; 3053c = inchar (typebuf .tb_buf + typebuf .tb_off + typebuf .tb_len , 3054typebuf .tb_buflen - typebuf .tb_off - typebuf .tb_len - 1 , 3055wait_time ); 3056 3057if (showcmd_idx != 0 ) { 3058pop_showcmd (); 3059 } 3060if (showing_partial == 1 ) { 3061if (State & MODE_INSERT ) { 3062edit_unputchar (); 3063 } 3064if ((State & MODE_CMDLINE ) 3065&& get_cmdline_info ()-> cmdbuff != NULL ) { 3066unputcmdline (); 3067 }else { 3068setcursor ();// put cursor back where it belongs 3069 } 3070 } 3071 3072if (c < 0 ) { 3073continue ;// end of input script reached 3074 } 3075if (c == NUL ) {// no character available 3076if (!advance ) { 3077break ; 3078 } 3079if (wait_tb_len > 0 ) {// timed out 3080timedout = true; 3081continue ; 3082 } 3083 }else {// allow mapping for just typed characters 3084while (typebuf .tb_buf [typebuf .tb_off + typebuf .tb_len ]!= NUL ) { 3085typebuf .tb_noremap [typebuf .tb_off + typebuf .tb_len ++ ]= RM_YES ; 3086 } 3087 } 3088 }// while (true) 3089 }// if (!character from stuffbuf) 3090 3091// if advance is false don't loop on NULs 3092 }while (c < 0 || (advance && c == NUL )); 3093 3094// The "INSERT" message is taken care of here: 3095// if we return an ESC to exit insert mode, the message is deleted 3096// if we don't return an ESC but deleted the message before, redisplay it 3097if (advance && p_smd && msg_silent == 0 && (State & MODE_INSERT )) { 3098if (c == ESC && !mode_deleted && !no_mapping && mode_displayed ) { 3099if (typebuf .tb_len && !KeyTyped ) { 3100redraw_cmdline = true;// delete mode later 3101 }else { 3102unshowmode (false); 3103 } 3104 }else if (c != ESC && mode_deleted ) { 3105if (typebuf .tb_len && !KeyTyped ) { 3106redraw_cmdline = true;// show mode later 3107 }else { 3108showmode (); 3109 } 3110 } 3111 } 3112 3113if (timedout && c == ESC ) { 3114// When recording there will be no timeout. Add an <Ignore> after the 3115// ESC to avoid that it forms a key code with following characters. 3116gotchars_ignore (); 3117 } 3118 3119vgetc_busy -- ; 3120 3121return c ; 3122} 3123 3124/// inchar() - get one character from 3125/// 1. a scriptfile 3126/// 2. the keyboard 3127/// 3128/// As many characters as we can get (up to 'maxlen') are put in "buf" and 3129/// NUL terminated (buffer length must be 'maxlen' + 1). 3130/// Minimum for "maxlen" is 3!!!! 3131/// 3132/// "tb_change_cnt" is the value of typebuf.tb_change_cnt if "buf" points into 3133/// it. When typebuf.tb_change_cnt changes (e.g., when a message is received 3134/// from a remote client) "buf" can no longer be used. "tb_change_cnt" is 0 3135/// otherwise. 3136/// 3137/// If we got an interrupt all input is read until none is available. 3138/// 3139/// If wait_time == 0 there is no waiting for the char. 3140/// If wait_time == n we wait for n msec for a character to arrive. 3141/// If wait_time == -1 we wait forever for a character to arrive. 3142/// 3143/// Return the number of obtained characters. 3144/// Return -1 when end of input script reached. 3145/// 3146/// @param wait_time milliseconds 3147static int inchar (uint8_t * buf ,int maxlen ,long wait_time ) 3148{ 3149int len = 0 ;// Init for GCC. 3150int retesc = false;// Return ESC with gotint. 3151const int tb_change_cnt = typebuf .tb_change_cnt ; 3152 3153if (wait_time == -1 || wait_time > 100 ) { 3154// flush output before waiting 3155ui_flush (); 3156 } 3157 3158// Don't reset these when at the hit-return prompt, otherwise an endless 3159// recursive loop may result (write error in swapfile, hit-return, timeout 3160// on char wait, flush swapfile, write error....). 3161if (State != MODE_HITRETURN ) { 3162did_outofmem_msg = false;// display out of memory message (again) 3163did_swapwrite_msg = false;// display swap file write error again 3164 } 3165 3166// Get a character from a script file if there is one. 3167// If interrupted: Stop reading script files, close them all. 3168ptrdiff_t read_size = -1 ; 3169while (curscript >=0 && read_size <=0 && !ignore_script ) { 3170char script_char ; 3171if (got_int 3172|| (read_size = file_read (& scriptin [curscript ],& script_char ,1 ))!= 1 ) { 3173// Reached EOF or some error occurred. 3174// Careful: closescript() frees typebuf.tb_buf[] and buf[] may 3175// point inside typebuf.tb_buf[]. Don't use buf[] after this! 3176closescript (); 3177// When reading script file is interrupted, return an ESC to get 3178// back to normal mode. 3179// Otherwise return -1, because typebuf.tb_buf[] has changed. 3180if (got_int ) { 3181retesc = true; 3182 }else { 3183return -1 ; 3184 } 3185 }else { 3186buf [0 ]= (uint8_t )script_char ; 3187len = 1 ; 3188 } 3189 } 3190 3191if (read_size <=0 ) {// Did not get a character from script. 3192// If we got an interrupt, skip all previously typed characters and 3193// return true if quit reading script file. 3194// Stop reading typeahead when a single CTRL-C was read, 3195// fill_input_buf() returns this when not able to read from stdin. 3196// Don't use buf[] here, closescript() may have freed typebuf.tb_buf[] 3197// and buf may be pointing inside typebuf.tb_buf[]. 3198if (got_int ) { 3199#define DUM_LEN (MAXMAPLEN * 3 + 3) 3200uint8_t dum [DUM_LEN + 1 ]; 3201 3202while (true) { 3203len = input_get (dum ,DUM_LEN ,0 ,0 ,NULL ); 3204if (len == 0 || (len == 1 && dum [0 ]== Ctrl_C )) { 3205break ; 3206 } 3207 } 3208return retesc ; 3209 } 3210 3211// Always flush the output characters when getting input characters 3212// from the user and not just peeking. 3213if (wait_time == -1 || wait_time > 10 ) { 3214ui_flush (); 3215 } 3216 3217// Fill up to a third of the buffer, because each character may be 3218// tripled below. 3219len = input_get (buf ,maxlen /3 , (int )wait_time ,tb_change_cnt ,NULL ); 3220 } 3221 3222// If the typebuf was changed further down, it is like nothing was added by 3223// this call. 3224if (typebuf_changed (tb_change_cnt )) { 3225return 0 ; 3226 } 3227 3228// Note the change in the typeahead buffer, this matters for when 3229// vgetorpeek() is called recursively, e.g. using getchar(1) in a timer 3230// function. 3231if (len > 0 && ++ typebuf .tb_change_cnt == 0 ) { 3232typebuf .tb_change_cnt = 1 ; 3233 } 3234 3235return fix_input_buffer (buf ,len ); 3236} 3237 3238/// Fix typed characters for use by vgetc(). 3239/// "buf[]" must have room to triple the number of bytes! 3240/// Returns the new length. 3241int fix_input_buffer (uint8_t * buf ,int len ) 3242FUNC_ATTR_NONNULL_ALL 3243{ 3244if (!using_script ()) { 3245// Should not escape K_SPECIAL reading input from the user because vim 3246// key codes keys are processed in input.c/input_enqueue. 3247buf [len ]= NUL ; 3248return len ; 3249 } 3250 3251// Reading from script, need to process special bytes 3252uint8_t * p = buf ; 3253 3254// Two characters are special: NUL and K_SPECIAL. 3255// Replace NUL by K_SPECIAL KS_ZERO KE_FILLER 3256// Replace K_SPECIAL by K_SPECIAL KS_SPECIAL KE_FILLER 3257for (int i = len ;-- i >=0 ;p ++ ) { 3258if (p [0 ]== NUL 3259|| (p [0 ]== K_SPECIAL 3260&& (i < 2 || p [1 ]!= KS_EXTRA ))) { 3261memmove (p + 3 ,p + 1 , (size_t )i ); 3262p [2 ]= (uint8_t )K_THIRD (p [0 ]); 3263p [1 ]= (uint8_t )K_SECOND (p [0 ]); 3264p [0 ]= K_SPECIAL ; 3265p += 2 ; 3266len += 2 ; 3267 } 3268 } 3269* p = NUL ;// add trailing NUL 3270return len ; 3271} 3272 3273/// Get a key stroke directly from the user. 3274/// 3275/// Ignores mouse clicks and scrollbar events, except a click for the left 3276/// button (used at the more prompt). 3277/// Doesn't use vgetc(), because it syncs undo and eats mapped characters. 3278/// Disadvantage: typeahead is ignored. 3279/// Translates the interrupt character for unix to ESC. 3280int get_keystroke (MultiQueue * events ) 3281{ 3282uint8_t * buf = NULL ; 3283int buflen = 150 ; 3284int len = 0 ; 3285int n ; 3286int save_mapped_ctrl_c = mapped_ctrl_c ; 3287 3288mod_mask = 0 ; 3289mapped_ctrl_c = 0 ;// mappings are not used here 3290while (true) { 3291// flush output before waiting 3292ui_flush (); 3293// Leave some room for check_termcode() to insert a key code into (max 3294// 5 chars plus NUL). And fix_input_buffer() can triple the number of 3295// bytes. 3296int maxlen = (buflen - 6 - len ) /3 ; 3297if (buf == NULL ) { 3298buf = xmalloc ((size_t )buflen ); 3299 }else if (maxlen < 10 ) { 3300// Need some more space. This might happen when receiving a long 3301// escape sequence. 3302buflen += 100 ; 3303buf = xrealloc (buf , (size_t )buflen ); 3304maxlen = (buflen - 6 - len ) /3 ; 3305 } 3306 3307// First time: blocking wait. Second time: wait up to 100ms for a 3308// terminal code to complete. 3309n = input_get (buf + len ,maxlen ,len == 0 ?-1 :100 ,0 ,events ); 3310if (n > 0 ) { 3311// Replace zero and K_SPECIAL by a special key code. 3312n = fix_input_buffer (buf + len ,n ); 3313len += n ; 3314 } 3315 3316if (n > 0 ) {// found a termcode: adjust length 3317len = n ; 3318 } 3319if (len == 0 ) {// nothing typed yet 3320continue ; 3321 } 3322 3323// Handle modifier and/or special key code. 3324n = buf [0 ]; 3325if (n == K_SPECIAL ) { 3326n = TO_SPECIAL (buf [1 ],buf [2 ]); 3327if (buf [1 ]== KS_MODIFIER 3328|| n == K_IGNORE 3329|| (is_mouse_key (n )&& n != K_LEFTMOUSE )) { 3330if (buf [1 ]== KS_MODIFIER ) { 3331mod_mask = buf [2 ]; 3332 } 3333len -= 3 ; 3334if (len > 0 ) { 3335memmove (buf ,buf + 3 , (size_t )len ); 3336 } 3337continue ; 3338 } 3339break ; 3340 } 3341if (MB_BYTE2LEN (n )> len ) { 3342// more bytes to get. 3343continue ; 3344 } 3345buf [len >=buflen ?buflen - 1 :len ]= NUL ; 3346n = utf_ptr2char ((char * )buf ); 3347break ; 3348 } 3349xfree (buf ); 3350 3351mapped_ctrl_c = save_mapped_ctrl_c ; 3352return merge_modifiers (n ,& mod_mask ); 3353} 3354 3355/// Function passed to do_cmdline() to get the command after a <Cmd> key from 3356/// typeahead. 3357char * getcmdkeycmd (int promptc ,void * cookie ,int indent ,bool do_concat ) 3358{ 3359garray_T line_ga ; 3360int c1 = -1 ; 3361int cmod = 0 ; 3362bool aborted = false; 3363 3364ga_init (& line_ga ,1 ,32 ); 3365 3366// no mapping for these characters 3367no_mapping ++ ; 3368 3369got_int = false; 3370while (c1 != NUL && !aborted ) { 3371ga_grow (& line_ga ,32 ); 3372 3373if (vgetorpeek (false)== NUL ) { 3374// incomplete <Cmd> is an error, because there is not much the user 3375// could do in this state. 3376emsg (_ (e_cmd_mapping_must_end_with_cr )); 3377aborted = true; 3378break ; 3379 } 3380 3381// Get one character at a time. 3382c1 = vgetorpeek (true); 3383 3384// Get two extra bytes for special keys 3385if (c1 == K_SPECIAL ) { 3386c1 = vgetorpeek (true); 3387int c2 = vgetorpeek (true); 3388if (c1 == KS_MODIFIER ) { 3389cmod = c2 ; 3390continue ; 3391 } 3392c1 = TO_SPECIAL (c1 ,c2 ); 3393 } 3394 3395if (got_int ) { 3396aborted = true; 3397 }else if (c1 == '\r' || c1 == '\n' ) { 3398c1 = NUL ;// end the line 3399 }else if (c1 == ESC ) { 3400aborted = true; 3401 }else if (c1 == K_COMMAND ) { 3402// give a nicer error message for this special case 3403emsg (_ (e_cmd_mapping_must_end_with_cr_before_second_cmd )); 3404aborted = true; 3405 }else if (c1 == K_SNR ) { 3406GA_CONCAT_LITERAL (& line_ga ,"<SNR>" ); 3407 }else { 3408if (cmod != 0 ) { 3409ga_append (& line_ga ,K_SPECIAL ); 3410ga_append (& line_ga ,KS_MODIFIER ); 3411ga_append (& line_ga , (uint8_t )cmod ); 3412 } 3413if (IS_SPECIAL (c1 )) { 3414ga_append (& line_ga ,K_SPECIAL ); 3415ga_append (& line_ga , (uint8_t )K_SECOND (c1 )); 3416ga_append (& line_ga , (uint8_t )K_THIRD (c1 )); 3417 }else { 3418ga_append (& line_ga , (uint8_t )c1 ); 3419 } 3420 } 3421 3422cmod = 0 ; 3423 } 3424 3425no_mapping -- ; 3426 3427if (aborted ) { 3428ga_clear (& line_ga ); 3429 }else if (promptc == ':' ) { 3430// Executing (do_cmdline()), not discarding (vim.on_key()): capture the payload. 3431atom_cmdline_set (K_COMMAND ,line_ga .ga_data , (size_t )line_ga .ga_len ); 3432 } 3433 3434return line_ga .ga_data ; 3435} 3436 3437/// Handle a Lua mapping: get its id from typeahead and execute its callback. 3438/// 3439/// @param may_repeat Save the mapping-id for redoing with "." later 3440/// @param discard Discard the keys instead of executing the callback. 3441/// 3442/// @return false if getting the id was aborted or mapping no longer exists, true otherwise. 3443bool map_execute_lua (bool may_repeat ,bool discard ) 3444{ 3445garray_T line_ga ; 3446int c1 = -1 ; 3447bool aborted = false; 3448 3449ga_init (& line_ga ,1 ,32 ); 3450 3451no_mapping ++ ; 3452 3453got_int = false; 3454while (c1 != NUL && !aborted ) { 3455ga_grow (& line_ga ,32 ); 3456// Get one character at a time. 3457c1 = vgetorpeek (true); 3458if (got_int ) { 3459aborted = true; 3460 }else if (c1 == '\r' || c1 == '\n' ) { 3461c1 = NUL ;// end the line 3462 }else { 3463ga_append (& line_ga , (uint8_t )c1 ); 3464 } 3465 } 3466 3467no_mapping -- ; 3468 3469if (aborted || discard ) { 3470ga_clear (& line_ga ); 3471return !aborted ; 3472 } 3473 3474const int id = atoi (line_ga .ga_data ); 3475const LuaRef ref = map_luaid_get (id ); 3476if (ref == LUA_NOREF ) { 3477ga_clear (& line_ga ); 3478emsg (_ (e_lua_mapping_gone )); 3479return false; 3480 } 3481if (may_repeat ) { 3482repeat_luamap = id ; 3483 } 3484 3485Error err = ERROR_INIT ; 3486Array args = ARRAY_DICT_INIT ; 3487nlua_call_ref (ref ,NULL ,args ,kRetNilBool ,NULL ,& err ); 3488if (ERROR_SET (& err )) { 3489semsg_multiline ("emsg" ,"E5108: %s" ,err .msg ); 3490api_clear_error (& err ); 3491 } 3492 3493ga_clear (& line_ga ); 3494return true; 3495} 3496 3497/// Wraps pasted text stream with K_PASTE_START and K_PASTE_END, and 3498/// appends to redo buffer and/or record buffer if needed. 3499/// Escapes all K_SPECIAL and NUL bytes in the content. 3500/// 3501/// @param state kFalse for the start of a paste 3502/// kTrue for the end of a paste 3503/// kNone for the content of a paste 3504/// @param str the content of the paste (only used when state is kNone) 3505void paste_store (const uint64_t channel_id ,const TriState state ,const String str ,const bool crlf ) 3506{ 3507if (State & MODE_CMDLINE ) { 3508return ; 3509 } 3510 3511const bool need_redo = !block_redo ; 3512const bool need_record = reg_recording != 0 && !is_internal_call (channel_id ); 3513 3514if (!need_redo && !need_record ) { 3515return ; 3516 } 3517 3518if (state != kNone ) { 3519const int c = state == kFalse ?K_PASTE_START :K_PASTE_END ; 3520if (need_redo ) { 3521if (state == kFalse && !(State & MODE_INSERT )) { 3522redo_new ((CmdSpec ){0 }); 3523 } 3524sb_add_char (& redobuff .cur .body ,c ); 3525 } 3526if (need_record ) { 3527sb_add_char (& recordbuff ,c ); 3528 } 3529return ; 3530 } 3531 3532const char * s = str .data ; 3533const char * const str_end = str .data + str .size ; 3534 3535while (s < str_end ) { 3536const char * start = s ; 3537while (s < str_end && (uint8_t )(* s )!= K_SPECIAL && * s != NUL 3538&& * s != NL && !(crlf && * s == CAR )) { 3539s ++ ; 3540 } 3541 3542if (s > start ) { 3543if (need_redo ) { 3544kv_concat_len (redobuff .cur .body ,start , (size_t )(s - start )); 3545 } 3546if (need_record ) { 3547kv_concat_len (recordbuff ,start , (size_t )(s - start )); 3548 } 3549 } 3550 3551if (s < str_end ) { 3552int c = (uint8_t )(* s ++ ); 3553if (crlf && c == CAR ) { 3554if (s < str_end && * s == NL ) { 3555s ++ ; 3556 } 3557c = NL ; 3558 } 3559if (need_redo ) { 3560sb_add_byte (& redobuff .cur .body ,c ); 3561 } 3562if (need_record ) { 3563sb_add_byte (& recordbuff ,c ); 3564 } 3565 } 3566 } 3567} 3568 3569/// Gets a paste stored by paste_store() from typeahead and repeats it. 3570void paste_repeat (int count ) 3571{ 3572garray_T ga = GA_INIT (1 ,32 ); 3573bool aborted = false; 3574 3575no_mapping ++ ; 3576 3577got_int = false; 3578while (!aborted ) { 3579ga_grow (& ga ,32 ); 3580uint8_t c1 = (uint8_t )vgetorpeek (true); 3581if (c1 == K_SPECIAL ) { 3582c1 = (uint8_t )vgetorpeek (true); 3583uint8_t c2 = (uint8_t )vgetorpeek (true); 3584int c = TO_SPECIAL (c1 ,c2 ); 3585if (c == K_PASTE_END ) { 3586break ; 3587 }else if (c == K_ZERO ) { 3588ga_append (& ga ,NUL ); 3589 }else if (c == K_SPECIAL ) { 3590ga_append (& ga ,K_SPECIAL ); 3591 }else { 3592ga_append (& ga ,K_SPECIAL ); 3593ga_append (& ga ,c1 ); 3594ga_append (& ga ,c2 ); 3595 } 3596 }else { 3597ga_append (& ga ,c1 ); 3598 } 3599aborted = got_int ; 3600 } 3601 3602no_mapping -- ; 3603 3604String str = cbuf_as_string (ga .ga_data , (size_t )ga .ga_len ); 3605Arena arena = ARENA_EMPTY ; 3606Error err = ERROR_INIT ; 3607for (int i = 0 ; !aborted && i < count ;i ++ ) { 3608nvim_paste (LUA_INTERNAL_CALL ,str , false,-1 ,& arena ,& err ); 3609aborted = ERROR_SET (& err ); 3610 } 3611api_clear_error (& err ); 3612arena_mem_free (arena_finish (& arena )); 3613ga_clear (& ga ); 3614}