robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// ex_getln.c: Functions for entering and editing an Ex command line. 2 3#include <assert.h> 4#include <inttypes.h> 5#include <limits.h> 6#include <stdbool.h> 7#include <stdio.h> 8#include <stdlib.h> 9#include <string.h> 10#include <time.h> 11 12#include "klib/kvec.h" 13#include "nvim/api/extmark.h" 14#include "nvim/api/private/defs.h" 15#include "nvim/api/private/helpers.h" 16#include "nvim/api/vim.h" 17#include "nvim/ascii_defs.h" 18#include "nvim/autocmd.h" 19#include "nvim/autocmd_defs.h" 20#include "nvim/buffer.h" 21#include "nvim/buffer_defs.h" 22#include "nvim/charset.h" 23#include "nvim/clipboard.h" 24#include "nvim/cmdexpand.h" 25#include "nvim/cmdexpand_defs.h" 26#include "nvim/cmdhist.h" 27#include "nvim/context.h" 28#include "nvim/cursor.h" 29#include "nvim/digraph.h" 30#include "nvim/drawscreen.h" 31#include "nvim/errors.h" 32#include "nvim/eval.h" 33#include "nvim/eval/typval.h" 34#include "nvim/eval/vars.h" 35#include "nvim/event/defs.h" 36#include "nvim/event/loop.h" 37#include "nvim/event/multiqueue.h" 38#include "nvim/ex_cmds.h" 39#include "nvim/ex_cmds_defs.h" 40#include "nvim/ex_docmd.h" 41#include "nvim/ex_eval.h" 42#include "nvim/ex_getln.h" 43#include "nvim/extmark.h" 44#include "nvim/garray.h" 45#include "nvim/garray_defs.h" 46#include "nvim/gettext_defs.h" 47#include "nvim/globals.h" 48#include "nvim/highlight_defs.h" 49#include "nvim/highlight_group.h" 50#include "nvim/input.h" 51#include "nvim/input_cmdatom.h" 52#include "nvim/insert.h" 53#include "nvim/keycodes.h" 54#include "nvim/lua/executor.h" 55#include "nvim/macros_defs.h" 56#include "nvim/main.h" 57#include "nvim/map_defs.h" 58#include "nvim/mapping.h" 59#include "nvim/mark.h" 60#include "nvim/mark_defs.h" 61#include "nvim/mbyte.h" 62#include "nvim/memline.h" 63#include "nvim/memory.h" 64#include "nvim/memory_defs.h" 65#include "nvim/message.h" 66#include "nvim/mouse.h" 67#include "nvim/move.h" 68#include "nvim/normal.h" 69#include "nvim/ops.h" 70#include "nvim/option.h" 71#include "nvim/option_defs.h" 72#include "nvim/option_vars.h" 73#include "nvim/os/input.h" 74#include "nvim/os/os.h" 75#include "nvim/path.h" 76#include "nvim/popupmenu.h" 77#include "nvim/pos_defs.h" 78#include "nvim/profile.h" 79#include "nvim/regexp.h" 80#include "nvim/regexp_defs.h" 81#include "nvim/register.h" 82#include "nvim/search.h" 83#include "nvim/state.h" 84#include "nvim/state_defs.h" 85#include "nvim/strings.h" 86#include "nvim/types_defs.h" 87#include "nvim/ui.h" 88#include "nvim/ui_defs.h" 89#include "nvim/undo.h" 90#include "nvim/undo_defs.h" 91#include "nvim/usercmd.h" 92#include "nvim/vim_defs.h" 93#include "nvim/viml/parser/expressions.h" 94#include "nvim/viml/parser/parser.h" 95#include "nvim/viml/parser/parser_defs.h" 96#include "nvim/window.h" 97 98/// Last value of prompt_id, incremented when doing new prompt 99static unsigned last_prompt_id = 0 ; 100 101// Struct to store the state of 'incsearch' highlighting. 102typedef struct { 103pos_T search_start ;// where 'incsearch' starts searching 104pos_T save_cursor ; 105handle_T winid ;// window where this state is valid 106viewstate_T init_viewstate ; 107viewstate_T old_viewstate ; 108pos_T match_start ; 109pos_T match_end ; 110bool did_incsearch ; 111bool incsearch_postponed ; 112}incsearch_state_T ; 113 114typedef struct { 115VimState state ; 116int firstc ; 117int count ; 118int indent ; 119int c ; 120bool gotesc ;// true when <ESC> just typed 121bool do_abbr ;// when true check for abbr. 122char * lookfor ;// string to match 123int lookforlen ; 124int hiscnt ;// current history line in use 125int save_hiscnt ;// history line before attempting 126// to jump to next match 127int histype ;// history type to be used 128incsearch_state_T is_state ; 129bool did_wild_list ;// did wild_list() recently 130int wim_index ;// index in wim_flags[] 131int save_msg_scroll ; 132int save_State ;// remember State when called 133int prev_cmdpos ; 134char * prev_cmdbuff ; 135char * save_p_icm ; 136bool skip_pum_redraw ; 137bool some_key_typed ;// one of the keys was typed 138// mouse drag and release events are ignored, unless they are 139// preceded with a mouse down event 140bool ignore_drag_release ; 141bool break_ctrl_c ; 142expand_T xpc ; 143OptInt * b_im_ptr ; 144buf_T * b_im_ptr_buf ;///< buffer where b_im_ptr is valid 145int cmdline_type ; 146bool event_cmdlineleavepre_triggered ; 147bool did_hist_navigate ; 148}CommandLineState ; 149 150typedef struct { 151buf_T * buf ; 152int save_b_p_ma ; 153int save_b_changed ; 154pos_T save_b_op_start ; 155pos_T save_b_op_end ; 156UndoCheckpoint undo_checkpoint ; 157}CpBufInfo ; 158 159typedef struct { 160win_T * win ; 161pos_T save_w_cursor ; 162viewstate_T save_viewstate ; 163int save_w_p_cul ; 164int save_w_p_cuc ; 165}CpWinInfo ; 166 167typedef struct { 168kvec_t (CpWinInfo )win_info ; 169kvec_t (CpBufInfo )buf_info ; 170bool save_hls ; 171cmdmod_T save_cmdmod ; 172garray_T save_view ; 173}CpInfo ; 174 175/// Return value when handling keys in command-line mode. 176enum { 177CMDLINE_NOT_CHANGED = 1 , 178CMDLINE_CHANGED = 2 , 179GOTO_NORMAL_MODE = 3 , 180PROCESS_NEXT_KEY = 4 , 181}; 182 183/// The current cmdline_info. It is initialized in getcmdline() and after that 184/// used by other functions. When invoking getcmdline() recursively it needs 185/// to be saved with save_cmdline() and restored with restore_cmdline(). 186static CmdlineInfo ccline ; 187 188static int new_cmdpos ;// position set by set_cmdline_pos() 189 190/// currently displayed block of context 191static Array cmdline_block = ARRAY_DICT_INIT ; 192 193/// Flag for command_line_handle_key to ignore <C-c> 194/// 195/// Used if it was received while processing highlight function in order for 196/// user interrupting highlight function to not interrupt command-line. 197static bool getln_interrupted_highlight = false; 198 199static int cedit_key = -1 ;///< key value of 'cedit' option 200 201#include "ex_getln.c.generated.h" 202 203static handle_T cmdpreview_bufnr = 0 ; 204static int cmdpreview_ns = 0 ; 205 206static void trigger_cmd_autocmd (int typechar ,event_T evt ) 207{ 208char typestr [2 ]= { (char )typechar ,NUL }; 209apply_autocmds (evt ,typestr ,typestr , false,curbuf ); 210} 211 212static void init_incsearch_state (incsearch_state_T * s ) 213{ 214s -> winid = curwin -> handle ; 215s -> match_start = curwin -> w_cursor ; 216s -> did_incsearch = false; 217s -> incsearch_postponed = false; 218clearpos (& s -> match_end ); 219s -> save_cursor = curwin -> w_cursor ;// may be restored later 220s -> search_start = curwin -> w_cursor ; 221save_viewstate (curwin ,& s -> init_viewstate ); 222save_viewstate (curwin ,& s -> old_viewstate ); 223} 224 225static void set_search_match (pos_T * t ) 226{ 227// First move cursor to end of match, then to the start. This 228// moves the whole match onto the screen when 'nowrap' is set. 229t -> lnum += Search .match_lines ; 230t -> col = Search .match_endcol ; 231if (t -> lnum > curbuf -> b_ml .ml_line_count ) { 232t -> lnum = curbuf -> b_ml .ml_line_count ; 233coladvance (curwin ,MAXCOL ); 234 } 235} 236 237/// Parses the :[range]s/foo like commands and returns details needed for 238/// incsearch and wildmenu completion. 239/// Returns true if pattern is valid. 240/// Sets skiplen, patlen, Search.first_line, and Search.last_line and magic if overruled. 241bool parse_pattern_and_range (pos_T * incsearch_start ,int * search_delim ,int * skiplen ,int * patlen , 242bool * is_magic ) 243FUNC_ATTR_NONNULL_ALL 244{ 245char * p ; 246bool delim_optional = false; 247const char * dummy ; 248magic_T magic = 0 ; 249 250* skiplen = 0 ; 251* patlen = ccline .cmdlen ; 252 253// Default range 254Search .first_line = 0 ; 255Search .last_line = MAXLNUM ; 256 257exarg_T ea = { 258 .line1 = 1 , 259 .line2 = 1 , 260 .cmd = ccline .cmdbuff , 261 .addr_type = ADDR_LINES , 262 }; 263 264cmdmod_T dummy_cmdmod ; 265// Skip over command modifiers 266parse_command_modifiers (& ea ,& dummy ,& dummy_cmdmod , true); 267 268// Skip over the range to find the command. 269char * cmd = skip_range (ea .cmd ,NULL ); 270if (vim_strchr ("sgvlu" , (uint8_t )(* cmd ))== NULL ) { 271return false; 272 } 273 274// Skip over command name to find pattern separator 275for (p = cmd ;ASCII_ISALPHA (* p );p ++ ) {} 276if (* skipwhite (p )== NUL ) { 277return false; 278 } 279 280if (strncmp (cmd ,"substitute" , (size_t )(p - cmd ))== 0 281|| strncmp (cmd ,"smagic" , (size_t )(p - cmd ))== 0 282|| strncmp (cmd ,"snomagic" , (size_t )MAX (p - cmd ,3 ))== 0 283|| strncmp (cmd ,"vglobal" , (size_t )(p - cmd ))== 0 ) { 284if (* cmd == 's' && cmd [1 ]== 'm' ) { 285* is_magic = true; 286 }else if (* cmd == 's' && cmd [1 ]== 'n' ) { 287* is_magic = false; 288 } 289 }else if (strncmp (cmd ,"sort" , (size_t )MAX (p - cmd ,3 ))== 0 290|| strncmp (cmd ,"uniq" , (size_t )MAX (p - cmd ,3 ))== 0 ) { 291// skip over ! and flags 292if (* p == '!' ) { 293p = skipwhite (p + 1 ); 294 } 295while (ASCII_ISALPHA (* (p = skipwhite (p )))) { 296p ++ ; 297 } 298if (* p == NUL ) { 299return false; 300 } 301 }else if (strncmp (cmd ,"vimgrep" , (size_t )MAX (p - cmd ,3 ))== 0 302|| strncmp (cmd ,"vimgrepadd" , (size_t )MAX (p - cmd ,8 ))== 0 303|| strncmp (cmd ,"lvimgrep" , (size_t )MAX (p - cmd ,2 ))== 0 304|| strncmp (cmd ,"lvimgrepadd" , (size_t )MAX (p - cmd ,9 ))== 0 305|| strncmp (cmd ,"global" , (size_t )(p - cmd ))== 0 ) { 306// skip optional "!" 307if (* p == '!' ) { 308p ++ ; 309if (* skipwhite (p )== NUL ) { 310return false; 311 } 312 } 313if (* cmd != 'g' ) { 314delim_optional = true; 315 } 316 }else { 317return false; 318 } 319 320p = skipwhite (p ); 321int delim = (delim_optional && vim_isIDc ((uint8_t )(* p ))) ?' ' :* p ++ ; 322* search_delim = delim ; 323 324char * end = skip_regexp_ex (p ,delim ,* is_magic ,NULL ,NULL ,& magic ); 325bool use_last_pat = end == p && * end == delim ; 326 327if (end == p && !use_last_pat ) { 328return false; 329 } 330 331// Skip if the pattern matches everything (e.g., for 'hlsearch') 332if (!use_last_pat ) { 333char c = * end ; 334* end = NUL ; 335bool empty = empty_pattern_magic (p , (size_t )(end - p ),magic ); 336* end = c ; 337if (empty ) { 338return false; 339 } 340 } 341 342// Found a non-empty pattern or // 343* skiplen = (int )(p - ccline .cmdbuff ); 344* patlen = (int )(end - p ); 345 346// Parse the address range 347pos_T save_cursor = curwin -> w_cursor ; 348curwin -> w_cursor = * incsearch_start ; 349 350parse_cmd_address (& ea ,& dummy , true); 351 352if (ea .addr_count > 0 ) { 353// Allow for reverse match. 354Search .first_line = MIN (ea .line2 ,ea .line1 ); 355Search .last_line = MAX (ea .line2 ,ea .line1 ); 356 }else if (cmd [0 ]== 's' && cmd [1 ]!= 'o' ) { 357// :s defaults to the current line 358Search .first_line = Search .last_line = curwin -> w_cursor .lnum ; 359 } 360 361curwin -> w_cursor = save_cursor ; 362return true; 363} 364 365/// Return true when 'incsearch' highlighting is to be done. 366/// Sets Search.first_line and Search.last_line to the address range. 367/// May change the last search pattern. 368static bool do_incsearch_highlighting (int firstc ,int * search_delim ,incsearch_state_T * is_state , 369int * skiplen ,int * patlen ,bool * magic ) 370{ 371bool retval = false; 372 373* skiplen = 0 ; 374* patlen = ccline .cmdlen ; 375 376if (!p_is || cmd_silent ) { 377return false; 378 } 379 380// By default search all lines 381Search .first_line = 0 ; 382Search .last_line = MAXLNUM ; 383 384if (firstc == '/' || firstc == '?' ) { 385* search_delim = firstc ; 386return true; 387 } 388 389if (firstc != ':' ) { 390return false; 391 } 392 393emsg_off ++ ; 394retval = parse_pattern_and_range (& is_state -> search_start ,search_delim , 395skiplen ,patlen ,magic ); 396emsg_off -- ; 397 398return retval ; 399} 400 401// May do 'incsearch' highlighting if desired. 402static void may_do_incsearch_highlighting (int firstc ,int count ,incsearch_state_T * s ) 403{ 404int skiplen ,patlen ; 405int search_delim ; 406bool magic = p_magic ; 407 408// Parsing range may already set the last search pattern. 409// NOTE: must call restore_last_search_pattern() before returning! 410save_last_search_pattern (); 411 412if (!do_incsearch_highlighting (firstc ,& search_delim ,s ,& skiplen ,& patlen ,& magic )) { 413restore_last_search_pattern (); 414finish_incsearch_highlighting (false,s , true); 415return ; 416 } 417 418// if there is a character waiting, search and redraw later 419if (char_avail ()) { 420restore_last_search_pattern (); 421s -> incsearch_postponed = true; 422return ; 423 } 424s -> incsearch_postponed = false; 425 426// Use the previous pattern for ":s//". 427char next_char = ccline .cmdbuff [skiplen + patlen ]; 428bool use_last_pat = patlen == 0 && skiplen > 0 429&& ccline .cmdbuff [skiplen - 1 ]== next_char ; 430 431if (patlen != 0 || use_last_pat ) { 432ui_busy_start (); 433ui_flush (); 434 } 435 436if (Search .first_line == 0 ) { 437// start at the original cursor position 438curwin -> w_cursor = s -> search_start ; 439 }else if (Search .first_line > curbuf -> b_ml .ml_line_count ) { 440// start after the last line 441curwin -> w_cursor .lnum = curbuf -> b_ml .ml_line_count ; 442curwin -> w_cursor .col = MAXCOL ; 443 }else { 444// start at the first line in the range 445curwin -> w_cursor .lnum = Search .first_line ; 446curwin -> w_cursor .col = 0 ; 447 } 448 449int found = 0 ;// do_search() result 450 451if (patlen != 0 || use_last_pat ) { 452int search_flags = SEARCH_OPT + SEARCH_NOOF + SEARCH_PEEK ; 453if (!p_hls ) { 454search_flags += SEARCH_KEEP ; 455 } 456if (Search .first_line != 0 ) { 457search_flags += SEARCH_START ; 458 } 459// Set the time limit to half a second. 460proftime_T tm = profile_setlimit (500 ); 461searchit_arg_T sia = { .sa_tm = & tm }; 462ccline .cmdbuff [skiplen + patlen ]= NUL ; 463emsg_off ++ ;// So it doesn't beep if bad expr 464found = do_search (NULL ,firstc == ':' ?'/' :firstc ,search_delim , 465ccline .cmdbuff + skiplen , (size_t )patlen ,count , 466search_flags ,magic ,& sia ); 467emsg_off -- ; 468ccline .cmdbuff [skiplen + patlen ]= next_char ; 469if (curwin -> w_cursor .lnum < Search .first_line 470|| curwin -> w_cursor .lnum > Search .last_line ) { 471// match outside of address range 472found = 0 ; 473curwin -> w_cursor = s -> search_start ; 474 } 475 476// if interrupted while searching, behave like it failed 477if (got_int ) { 478vpeekc ();// remove <C-C> from input stream 479got_int = false;// don't abandon the command line 480found = 0 ; 481 }else if (char_avail ()) { 482// cancelled searching because a char was typed 483s -> incsearch_postponed = true; 484 } 485ui_busy_stop (); 486 }else { 487set_no_hlsearch (true);// turn off previous highlight 488redraw_all_later (UPD_SOME_VALID ); 489 } 490 491Search .hl_match = found != 0 ;// add or remove search match position 492 493// first restore the old curwin values, so the screen is 494// positioned in the same way as the actual search command 495restore_viewstate (curwin ,& s -> old_viewstate ); 496changed_cline_bef_curs (curwin ); 497update_topline (curwin ); 498 499pos_T end_pos = curwin -> w_cursor ; 500if (found != 0 ) { 501s -> match_start = curwin -> w_cursor ; 502set_search_match (& curwin -> w_cursor ); 503validate_cursor (curwin ); 504s -> match_end = curwin -> w_cursor ; 505curwin -> w_cursor = end_pos ; 506end_pos = s -> match_end ; 507 } 508 509// Disable 'hlsearch' highlighting if the pattern matches 510// everything. Avoids a flash when typing "foo\|". 511if (!use_last_pat ) { 512next_char = ccline .cmdbuff [skiplen + patlen ]; 513ccline .cmdbuff [skiplen + patlen ]= NUL ; 514if (empty_pattern (ccline .cmdbuff + skiplen , (size_t )patlen ,search_delim ) 515&& !Search .no_hlsearch ) { 516redraw_all_later (UPD_SOME_VALID ); 517set_no_hlsearch (true); 518 } 519ccline .cmdbuff [skiplen + patlen ]= next_char ; 520 } 521 522validate_cursor (curwin ); 523 524// May redraw the status line to show the cursor position. 525if (p_ru && (curwin -> w_status_height > 0 || global_stl_height ()> 0 )) { 526curwin -> w_redr_status = true; 527 } 528 529redraw_later (curwin ,UPD_SOME_VALID ); 530update_screen (); 531Search .hl_match = false; 532restore_last_search_pattern (); 533 534// Leave it at the end to make CTRL-R CTRL-W work. But not when beyond the 535// end of the pattern, e.g. for ":s/pat/". 536if (ccline .cmdbuff [skiplen + patlen ]!= NUL ) { 537curwin -> w_cursor = s -> search_start ; 538 }else if (found != 0 ) { 539curwin -> w_cursor = end_pos ; 540curwin -> w_valid_cursor = end_pos ;// mark as valid for cmdline_show redraw 541 } 542 543msg_starthere (); 544redrawcmdline (); 545s -> did_incsearch = true; 546// Fire WinScrolled/WinResized last, after all state is finalized: the 547// autocmd may mutate curwin or ccline via arbitrary user code. 548may_trigger_win_scrolled_resized (); 549} 550 551// When CTRL-L typed: add character from the match to the pattern. 552// May set "*c" to the added character. 553// Return OK when calling command_line_not_changed. 554static int may_add_char_to_search (int firstc ,int * c ,incsearch_state_T * s ) 555FUNC_ATTR_NONNULL_ALL 556{ 557int skiplen ,patlen ; 558int search_delim ; 559bool magic = p_magic ; 560 561// Parsing range may already set the last search pattern. 562// NOTE: must call restore_last_search_pattern() before returning! 563save_last_search_pattern (); 564 565// Add a character from under the cursor for 'incsearch' 566if (!do_incsearch_highlighting (firstc ,& search_delim ,s ,& skiplen , 567& patlen ,& magic )) { 568restore_last_search_pattern (); 569return FAIL ; 570 } 571restore_last_search_pattern (); 572 573if (s -> did_incsearch ) { 574curwin -> w_cursor = s -> match_end ; 575* c = gchar_cursor (); 576if (* c != NUL ) { 577// If 'ignorecase' and 'smartcase' are set and the 578// command line has no uppercase characters, convert 579// the character to lowercase 580if (p_ic && p_scs 581&& !pat_has_uppercase (ccline .cmdbuff + skiplen )) { 582* c = mb_tolower (* c ); 583 } 584if (* c == search_delim 585|| vim_strchr ((p_magic ?"\\~^$.*[" :"\\^$" ),* c )!= NULL ) { 586// put a backslash before special characters 587stuffcharReadbuff (* c ); 588* c = '\\' ; 589 } 590// add any composing characters 591if (utf_char2len (* c )!= utfc_ptr2len (get_cursor_pos_ptr ())) { 592const int save_c = * c ; 593while (utf_char2len (* c )!= utfc_ptr2len (get_cursor_pos_ptr ())) { 594curwin -> w_cursor .col += utf_char2len (* c ); 595* c = gchar_cursor (); 596stuffcharReadbuff (* c ); 597 } 598* c = save_c ; 599 } 600return FAIL ; 601 } 602 } 603return OK ; 604} 605 606static void finish_incsearch_highlighting (bool gotesc ,incsearch_state_T * s , 607bool call_update_screen ) 608{ 609if (!s -> did_incsearch ) { 610return ; 611 } 612 613s -> did_incsearch = false; 614if (gotesc ) { 615curwin -> w_cursor = s -> save_cursor ; 616 }else { 617if (!equalpos (s -> save_cursor ,s -> search_start )) { 618// put the '" mark at the original position 619curwin -> w_cursor = s -> save_cursor ; 620setpcmark (); 621 } 622curwin -> w_cursor = s -> search_start ; 623 } 624restore_viewstate (curwin ,& s -> old_viewstate ); 625Search .hl_match = false; 626 627// by default search all lines 628Search .first_line = 0 ; 629Search .last_line = MAXLNUM ; 630 631validate_cursor (curwin );// needed for TAB 632status_redraw_all (); 633redraw_all_later (UPD_SOME_VALID ); 634if (call_update_screen ) { 635update_screen (); 636may_trigger_win_scrolled_resized (); 637 } 638} 639 640/// Initialize the current command-line info. 641static void init_ccline (int firstc ,int indent ) 642{ 643ccline .overstrike = false;// always start in insert mode 644 645assert (indent >=0 ); 646 647// set some variables for redrawcmd() 648ccline .cmdfirstc = (firstc == '@' ?0 :firstc ); 649ccline .cmdindent = (firstc > 0 ?indent :0 ); 650 651// alloc initial ccline.cmdbuff 652alloc_cmdbuff (indent + 50 ); 653ccline .cmdlen = ccline .cmdpos = 0 ; 654ccline .cmdbuff [0 ]= NUL ; 655 656ccline .last_colors = (ColoredCmdline ){ .cmdbuff = NULL , 657 .colors = KV_INITIAL_VALUE }; 658sb_text_start_cmdline (); 659 660// autoindent for :insert and :append 661if (firstc <=0 ) { 662memset (ccline .cmdbuff ,' ' , (size_t )indent ); 663ccline .cmdbuff [indent ]= NUL ; 664ccline .cmdpos = indent ; 665ccline .cmdspos = indent ; 666ccline .cmdlen = indent ; 667 } 668} 669 670static void ui_ext_cmdline_hide (bool abort ) 671{ 672if (ui_has (kUICmdline )) { 673cmdline_was_last_drawn = false; 674ccline .redraw_state = kCmdRedrawNone ; 675ui_call_cmdline_hide (ccline .level ,abort ); 676 } 677} 678 679/// Internal entry point for cmdline mode. 680/// 681/// @param count only used for incremental search 682/// @param indent indent for inside conditionals 683/// @param clear_ccline clear ccline first 684static uint8_t * command_line_enter (int firstc ,int count ,int indent ,bool clear_ccline ) 685{ 686// can be invoked recursively, identify each level 687static int cmdline_level = 0 ; 688cmdline_level ++ ; 689 690bool save_cmdpreview = cmdpreview ; 691cmdpreview = false; 692CommandLineState state = { 693 .firstc = firstc , 694 .count = count , 695 .indent = indent , 696 .save_msg_scroll = msg_scroll , 697 .save_State = State , 698 .prev_cmdpos = -1 , 699 .ignore_drag_release = true, 700 }; 701CommandLineState * s = & state ; 702s -> save_p_icm = xstrdup (p_icm ); 703init_incsearch_state (& s -> is_state ); 704CmdlineInfo save_ccline ; 705bool did_save_ccline = false; 706 707if (ccline .cmdbuff != NULL ) { 708// Currently ccline can never be in use if clear_ccline is false. 709// Some changes will be needed if this is no longer the case. 710assert (clear_ccline ); 711// Being called recursively. Since ccline is global, we need to save 712// the current buffer and restore it when returning. 713save_cmdline (& save_ccline ); 714did_save_ccline = true; 715 }else if (clear_ccline ) { 716CLEAR_FIELD (ccline ); 717 } 718 719if (s -> firstc == -1 ) { 720s -> firstc = NUL ; 721s -> break_ctrl_c = true; 722 } 723 724init_ccline (s -> firstc ,s -> indent ); 725assert (ccline .cmdbuff != NULL ); 726ccline .prompt_id = last_prompt_id ++ ; 727ccline .level = cmdline_level ; 728 729if (cmdline_level == 50 ) { 730// Somehow got into a loop recursively calling getcmdline(), bail out. 731emsg (_ (e_command_too_recursive )); 732 gototheend ; 733 } 734 735ExpandInit (& s -> xpc ); 736ccline .xpc = & s -> xpc ; 737clear_cmdline_orig (); 738 739cmdmsg_rl = (curwin -> w_p_rl && * curwin -> w_p_rlc == 's' 740&& (s -> firstc == '/' || s -> firstc == '?' )); 741 742msg_grid_validate (); 743 744redir_off = true;// don't redirect the typed command 745if (!cmd_silent ) { 746gotocmdline (true); 747redrawcmdprompt ();// draw prompt or indent 748ccline .cmdspos = cmd_startcol (); 749 } 750s -> xpc .xp_context = EXPAND_NOTHING ; 751s -> xpc .xp_backslash = XP_BS_NONE ; 752#ifndef BACKSLASH_IN_FILENAME 753s -> xpc .xp_shell = false; 754#endif 755 756if (ccline .input_fn ) { 757s -> xpc .xp_context = ccline .xp_context ; 758s -> xpc .xp_pattern = ccline .cmdbuff ; 759s -> xpc .xp_arg = ccline .xp_arg ; 760 } 761 762// Avoid scrolling when called by a recursive do_cmdline(), e.g. when 763// doing ":@0" when register 0 doesn't contain a CR. 764msg_scroll = false; 765 766State = MODE_CMDLINE ; 767 768if (s -> firstc == '/' || s -> firstc == '?' || s -> firstc == '@' ) { 769// Use ":lmap" mappings for search pattern and input(). 770if (curbuf -> b_p_imsearch == B_IMODE_USE_INSERT ) { 771s -> b_im_ptr = & curbuf -> b_p_iminsert ; 772 }else { 773s -> b_im_ptr = & curbuf -> b_p_imsearch ; 774 } 775s -> b_im_ptr_buf = curbuf ; 776if (* s -> b_im_ptr == B_IMODE_LMAP ) { 777State |=MODE_LANGMAP ; 778 } 779 } 780 781setmouse (); 782 783s -> cmdline_type = firstc > 0 ?firstc :'-' ; 784Error err = ERROR_INIT ; 785char firstcbuf [2 ]; 786firstcbuf [0 ]= (char )s -> cmdline_type ; 787firstcbuf [1 ]= 0 ; 788 789if (has_event (EVENT_CMDLINEENTER )) { 790save_v_event_T save_v_event ; 791dict_T * dict = get_v_event (& save_v_event ); 792 793// set v:event to a dictionary with information about the commandline 794tv_dict_add_str (dict ,S_LEN ("cmdtype" ),firstcbuf ); 795tv_dict_add_nr (dict ,S_LEN ("cmdlevel" ),ccline .level ); 796tv_dict_set_keys_readonly (dict ); 797TRY_WRAP (& err , { 798apply_autocmds (EVENT_CMDLINEENTER ,firstcbuf ,firstcbuf , false,curbuf ); 799restore_v_event (dict ,& save_v_event ); 800 }); 801 802if (ERROR_SET (& err )) { 803if (!ui_has (kUIMessages )) { 804msg_putchar ('\n' ); 805 } 806msg_scroll = true; 807msg_puts_hl (err .msg ,HLF_E , true); 808api_clear_error (& err ); 809redrawcmd (); 810 } 811err = ERROR_INIT ; 812 } 813may_trigger_modechanged (); 814 815init_history (); 816s -> hiscnt = get_hislen ();// set hiscnt to impossible history value 817s -> histype = hist_char2type (s -> firstc ); 818do_digraph (-1 );// init digraph typeahead 819 820// If something above caused an error, reset the flags, we do want to type 821// and execute commands. Display may be messed up a bit. 822if (did_emsg ) { 823redrawcmd (); 824 } 825 826// Redraw the statusline in case it uses the current mode using the mode() 827// function. 828if (!cmd_silent ) { 829bool found_one = false; 830 831FOR_ALL_WINDOWS_IN_TAB (wp ,curtab ) { 832if (* p_stl != NUL || * wp -> w_p_stl != NUL || * p_wbr != NUL || * wp -> w_p_wbr != NUL ) { 833wp -> w_redr_status = true; 834found_one = true; 835 } 836 } 837 838if (* p_tal != NUL ) { 839redraw_tabline = true; 840found_one = true; 841 } 842 843if (redraw_custom_title_later ()) { 844found_one = true; 845 } 846 847if (found_one ) { 848redraw_statuslines (); 849 } 850 } 851 852did_emsg = false; 853got_int = false; 854s -> state .check = command_line_check ; 855s -> state .execute = command_line_execute ; 856 857state_enter (& s -> state ); 858 859// Trigger CmdlineLeavePre autocommands if not already triggered. 860if (!s -> event_cmdlineleavepre_triggered ) { 861set_vim_var_char (s -> c );// Set v:char 862trigger_cmd_autocmd (s -> cmdline_type ,EVENT_CMDLINELEAVEPRE ); 863 } 864 865if (has_event (EVENT_CMDLINELEAVE )) { 866save_v_event_T save_v_event ; 867dict_T * dict = get_v_event (& save_v_event ); 868 869tv_dict_add_str (dict ,S_LEN ("cmdtype" ),firstcbuf ); 870tv_dict_add_nr (dict ,S_LEN ("cmdlevel" ),ccline .level ); 871tv_dict_set_keys_readonly (dict ); 872// not readonly: 873tv_dict_add_bool (dict ,S_LEN ("abort" ), 874s -> gotesc ?kBoolVarTrue :kBoolVarFalse ); 875set_vim_var_char (s -> c );// Set v:char 876TRY_WRAP (& err , { 877apply_autocmds (EVENT_CMDLINELEAVE ,firstcbuf ,firstcbuf , false,curbuf ); 878// error printed below, to avoid redraw issues 879 }); 880if (tv_dict_get_number (dict ,"abort" )!= 0 ) { 881s -> gotesc = true; 882 } 883restore_v_event (dict ,& save_v_event ); 884 } 885 886cmdmsg_rl = false; 887 888// We could have reached here without having a chance to clean up wild menu 889// if certain special keys like <Esc> or <C-\> were used as wildchar. Make 890// sure to still clean up to avoid memory corruption. 891if (cmdline_pum_active ()) { 892cmdline_pum_remove (false); 893 }else { 894// A previous cmdline_pum_remove() may have deferred redraw. 895pum_check_clear (); 896 } 897wildmenu_cleanup (& ccline ); 898s -> did_wild_list = false; 899s -> wim_index = 0 ; 900 901ExpandCleanup (& s -> xpc ); 902ccline .xpc = NULL ; 903clear_cmdline_orig (); 904 905finish_incsearch_highlighting (s -> gotesc ,& s -> is_state , false); 906 907if (ccline .cmdbuff != NULL ) { 908// Put line in history buffer (":" and "=" only when it was typed). 909if (s -> histype != HIST_INVALID 910&& ccline .cmdlen 911&& s -> firstc != NUL 912&& (s -> some_key_typed || s -> histype == HIST_SEARCH )) { 913add_to_history (s -> histype ,ccline .cmdbuff , (size_t )ccline .cmdlen , true, 914s -> histype == HIST_SEARCH ?s -> firstc :NUL ); 915if (s -> firstc == ':' ) { 916xfree (new_last_cmdline ); 917new_last_cmdline = xstrnsave (ccline .cmdbuff , (size_t )ccline .cmdlen ); 918 } 919 } 920 921if (!s -> gotesc && ccline .level == 1 ) { 922// An accepted toplevel cmdline is the executing command's payload (":cnext<CR>", "/pat<CR>"). 923atom_cmdline_set (s -> firstc ,ccline .cmdbuff , (size_t )ccline .cmdlen ); 924 } 925 926if (s -> gotesc ) { 927abandon_cmdline (); 928 } 929 } 930 931// If the screen was shifted up, redraw the whole screen (later). 932// If the line is too long, clear it, so ruler and shown command do 933// not get printed in the middle of it. 934msg_check (); 935if (p_ch == 0 && !ui_has (kUIMessages )) { 936set_must_redraw (UPD_VALID ); 937 } 938msg_scroll = s -> save_msg_scroll ; 939redir_off = false; 940 941if (ERROR_SET (& err )) { 942if (!ui_has (kUIMessages )) { 943msg_putchar ('\n' ); 944 } 945emsg (err .msg ); 946did_emsg = false; 947api_clear_error (& err ); 948 } 949 950// When the command line was typed, no need for a wait-return prompt. 951if (s -> some_key_typed && !ERROR_SET (& err )) { 952need_wait_return = false; 953 } 954 955set_option_direct (kOptInccommand ,CSTR_AS_OBJ (s -> save_p_icm ),0 ,SID_NONE ); 956State = s -> save_State ; 957if (cmdpreview != save_cmdpreview ) { 958cmdpreview = save_cmdpreview ;// restore preview state 959redraw_all_later (UPD_SOME_VALID ); 960 } 961may_trigger_modechanged (); 962setmouse (); 963sb_text_end_cmdline (); 964 965theend : 966xfree (s -> save_p_icm ); 967xfree (ccline .last_colors .cmdbuff ); 968kv_destroy (ccline .last_colors .colors ); 969 970char * p = ccline .cmdbuff ; 971 972if (ui_has (kUICmdline )) { 973ui_ext_cmdline_hide (s -> gotesc ); 974 } 975if (!cmd_silent ) { 976redraw_custom_title_later (); 977status_redraw_all ();// redraw to show mode change 978 } 979 980cmdline_level -- ; 981 982if (did_save_ccline ) { 983restore_cmdline (& save_ccline ); 984 }else { 985ccline .cmdbuff = NULL ; 986 } 987 988xfree (s -> prev_cmdbuff ); 989return (uint8_t * )p ; 990} 991 992static int command_line_check (VimState * state ) 993{ 994CommandLineState * s = (CommandLineState * )state ; 995 996s -> prev_cmdpos = ccline .cmdpos ; 997XFREE_CLEAR (s -> prev_cmdbuff ); 998 999redir_off = true;// Don't redirect the typed command. 1000// Repeated, because a ":redir" inside 1001// completion may switch it on. 1002quit_more = false;// reset after CTRL-D which had a more-prompt 1003 1004did_emsg = false;// There can't really be a reason why an error 1005// that occurs while typing a command should 1006// cause the command not to be executed. 1007 1008if (ex_normal_busy == 0 && stuff_empty ()&& typebuf .tb_len == 0 ) { 1009// There is no pending input from sources other than user input, so 1010// Vim is going to wait for the user to type a key. Consider the 1011// command line typed even if next key will trigger a mapping. 1012s -> some_key_typed = true; 1013 } 1014 1015// Trigger SafeState if nothing is pending. 1016may_trigger_safestate (s -> xpc .xp_numfiles <=0 ); 1017 1018if (ccline .cmdbuff != NULL ) { 1019s -> prev_cmdbuff = xstrdup (ccline .cmdbuff ); 1020 } 1021 1022// Defer screen update to avoid pum flicker during wildtrigger() 1023if (s -> c == K_WILD && s -> firstc != '@' ) { 1024s -> skip_pum_redraw = true; 1025 } 1026 1027cursorcmd ();// set the cursor on the right spot 1028ui_cursor_shape (); 1029return 1 ; 1030} 1031 1032/// Handle CTRL-\ pressed in Command-line mode: 1033/// - CTRL-\ CTRL-N or CTRL-\ CTRL-G goes to Normal mode. 1034/// - CTRL-\ e prompts for an expression. 1035static int command_line_handle_ctrl_bsl (CommandLineState * s ) 1036{ 1037no_mapping ++ ; 1038allow_keys ++ ; 1039s -> c = plain_vgetc (); 1040no_mapping -- ; 1041allow_keys -- ; 1042 1043// CTRL-\ e doesn't work when obtaining an expression, unless it 1044// is in a mapping. 1045if (s -> c != Ctrl_N 1046&& s -> c != Ctrl_G 1047&& (s -> c != 'e' 1048|| (ccline .cmdfirstc == '=' && KeyTyped ) 1049|| cmdline_star > 0 )) { 1050vungetc (s -> c ); 1051return PROCESS_NEXT_KEY ; 1052 } 1053 1054if (s -> c == 'e' ) { 1055// Replace the command line with the result of an expression. 1056// This will call getcmdline() recursively in get_expr_register(). 1057if (ccline .cmdpos == ccline .cmdlen ) { 1058new_cmdpos = 99999 ;// keep it at the end 1059 }else { 1060new_cmdpos = ccline .cmdpos ; 1061 } 1062 1063s -> c = get_expr_register (); 1064if (s -> c == '=' ) { 1065// Evaluate the expression. Set "textlock" to avoid nasty things 1066// like going to another buffer. 1067textlock ++ ; 1068char * p = get_expr_line (); 1069textlock -- ; 1070 1071if (p != NULL ) { 1072int len = (int )strlen (p ); 1073realloc_cmdbuff (len + 1 ); 1074ccline .cmdlen = len ; 1075STRCPY (ccline .cmdbuff ,p ); 1076xfree (p ); 1077 1078// Restore the cursor or use the position set with 1079// set_cmdline_pos(). 1080ccline .cmdpos = MIN (ccline .cmdlen ,new_cmdpos ); 1081 1082KeyTyped = false;// Don't do p_wc completion. 1083redrawcmd (); 1084return CMDLINE_CHANGED ; 1085 } 1086 } 1087beep_flush (); 1088got_int = false;// don't abandon the command line 1089did_emsg = false; 1090emsg_on_display = false; 1091redrawcmd (); 1092return CMDLINE_NOT_CHANGED ; 1093 } 1094 1095s -> gotesc = true;// will free ccline.cmdbuff after putting it in history 1096return GOTO_NORMAL_MODE ; 1097} 1098 1099/// Completion for 'wildchar' or 'wildcharm' key. 1100/// - hitting <ESC> twice means: abandon command line. 1101/// - wildcard expansion is only done when the 'wildchar' key is really 1102/// typed, not when it comes from a macro 1103/// @return CMDLINE_CHANGED if command line is changed or CMDLINE_NOT_CHANGED. 1104static int command_line_wildchar_complete (CommandLineState * s ) 1105{ 1106int res ; 1107int options = WILD_NO_BEEP ; 1108bool escape = s -> firstc != '@' ; 1109bool redraw_if_menu_empty = s -> c == K_WILD ; 1110bool wim_noselect = p_wmnu && (wim_flags [0 ]& kOptWimFlagNoselect )!= 0 ; 1111bool wim_noinsert = p_wmnu && (wim_flags [0 ]& kOptWimFlagNoinsert )!= 0 ; 1112 1113if (wim_flags [s -> wim_index ]& kOptWimFlagLastused ) { 1114options |=WILD_BUFLASTUSED ; 1115 } 1116if (s -> xpc .xp_numfiles > 0 ) {// typed p_wc at least twice 1117// If "list" is present, list matches unless already listed 1118if (s -> xpc .xp_numfiles > 1 1119&& !s -> did_wild_list 1120&& (wim_flags [s -> wim_index ]& kOptWimFlagList )) { 1121showmatches (& s -> xpc , false, true,p_wmnu ?wim_flags [s -> wim_index ] :0 ); 1122redrawcmd (); 1123s -> did_wild_list = true; 1124 } 1125if (wim_flags [s -> wim_index ]& kOptWimFlagLongest ) { 1126res = nextwild (& s -> xpc ,WILD_LONGEST ,options ,escape ); 1127 }else if (wim_flags [s -> wim_index ]& kOptWimFlagFull ) { 1128res = nextwild (& s -> xpc ,WILD_NEXT ,options ,escape ); 1129 }else { 1130res = OK ;// don't insert 'wildchar' now 1131 } 1132 }else {// typed p_wc first time 1133bool wim_longest = (wim_flags [0 ]& kOptWimFlagLongest ); 1134bool wim_list = (wim_flags [0 ]& kOptWimFlagList ); 1135bool wim_full = (wim_flags [0 ]& kOptWimFlagFull ); 1136 1137s -> wim_index = 0 ; 1138if (s -> c == p_wc || s -> c == p_wcm || s -> c == K_WILD || s -> c == Ctrl_Z ) { 1139options |=WILD_MAY_EXPAND_PATTERN ; 1140if (s -> c == K_WILD ) { 1141options |=WILD_FUNC_TRIGGER ; 1142 } 1143s -> xpc .xp_pre_incsearch_pos = s -> is_state .search_start ; 1144 } 1145int cmdpos_before = ccline .cmdpos ; 1146 1147// if 'wildmode' first contains "longest", get longest 1148// common part 1149if (wim_longest ) { 1150res = nextwild (& s -> xpc ,WILD_LONGEST ,options ,escape ); 1151 }else { 1152if (wim_noselect || (wim_list && !wim_full )) { 1153options |=WILD_NOSELECT ; 1154 } 1155if (wim_noinsert ) { 1156options |=WILD_NOINSERT ; 1157 } 1158res = nextwild (& s -> xpc ,WILD_EXPAND_KEEP ,options ,escape ); 1159 } 1160 1161// Remove popup menu if no completion items are available 1162if (redraw_if_menu_empty && s -> xpc .xp_numfiles <=0 ) { 1163pum_check_clear (); 1164 } 1165 1166// if interrupted while completing, behave like it failed 1167if (got_int ) { 1168vpeekc ();// remove <C-C> from input stream 1169got_int = false;// don't abandon the command line 1170ExpandOne (& s -> xpc ,NULL ,NULL ,0 ,WILD_FREE ); 1171s -> xpc .xp_context = EXPAND_NOTHING ; 1172return CMDLINE_CHANGED ; 1173 } 1174 1175// Display matches 1176if (res == OK && s -> xpc .xp_numfiles > ((wim_noselect || wim_noinsert ) ?0 :1 )) { 1177if (wim_longest ) { 1178bool found_longest_prefix = (ccline .cmdpos != cmdpos_before ); 1179bool show_menu = p_wmnu && wim_full ; 1180if (wim_list || show_menu ) { 1181showmatches (& s -> xpc ,show_menu ,wim_list ,kOptWimFlagNoselect ); 1182 }else if (!found_longest_prefix ) { 1183bool wim_list_next = (wim_flags [1 ]& kOptWimFlagList ); 1184bool wim_full_next = (wim_flags [1 ]& kOptWimFlagFull ); 1185bool wim_noselect_next = (wim_flags [1 ]& kOptWimFlagNoselect ); 1186bool wim_noinsert_next = (wim_flags [1 ]& kOptWimFlagNoinsert ); 1187if (wim_list_next 1188|| (p_wmnu && (wim_full_next || wim_noselect_next || wim_noinsert_next ))) { 1189if (wim_full_next && !wim_noselect_next && !wim_noinsert_next ) { 1190nextwild (& s -> xpc ,WILD_NEXT ,options ,escape ); 1191 }else { 1192showmatches (& s -> xpc ,p_wmnu && (wim_noselect_next || wim_noinsert_next ), 1193wim_list_next ,p_wmnu ?wim_flags [1 ] :0 ); 1194 } 1195if (wim_list_next ) { 1196s -> did_wild_list = true; 1197 } 1198 } 1199 } 1200 }else { 1201bool show_menu = p_wmnu && (wim_full || wim_noselect || wim_noinsert ); 1202if (wim_list || show_menu ) { 1203showmatches (& s -> xpc ,show_menu ,wim_list ,p_wmnu ?wim_flags [0 ] :0 ); 1204 }else { 1205vim_beep (kOptBoFlagWildmode ); 1206 } 1207 } 1208 1209redrawcmd (); 1210if (wim_list ) { 1211s -> did_wild_list = true; 1212 } 1213 }else if (s -> xpc .xp_numfiles == -1 ) { 1214s -> xpc .xp_context = EXPAND_NOTHING ; 1215 } 1216 } 1217 1218if (s -> wim_index < 3 ) { 1219s -> wim_index ++ ; 1220 } 1221 1222if (s -> c == ESC ) { 1223s -> gotesc = true; 1224 } 1225 1226return (res == OK ) ?CMDLINE_CHANGED :CMDLINE_NOT_CHANGED ; 1227} 1228 1229static void command_line_end_wildmenu (CommandLineState * s ,bool key_is_wc ,int c ) 1230{ 1231if (cmdline_pum_active ()) { 1232if (c != -1 ) { 1233s -> skip_pum_redraw = (s -> skip_pum_redraw && !key_is_wc 1234&& !ascii_iswhite (c ) 1235&& (vim_isprintc (c ) 1236|| c == K_BS || c == Ctrl_H || c == K_DEL 1237|| c == K_KDEL || c == Ctrl_W || c == Ctrl_U )); 1238 } 1239cmdline_pum_remove (c != -1 && s -> skip_pum_redraw ); 1240 } 1241if (s -> xpc .xp_numfiles != -1 ) { 1242ExpandOne (& s -> xpc ,NULL ,NULL ,0 ,WILD_FREE ); 1243 } 1244s -> did_wild_list = false; 1245if (!p_wmnu || (c != K_UP && c != K_DOWN )) { 1246s -> xpc .xp_context = EXPAND_NOTHING ; 1247 } 1248s -> wim_index = 0 ; 1249wildmenu_cleanup (& ccline ); 1250} 1251 1252static int command_line_execute (VimState * state ,int key ) 1253{ 1254if (key == K_IGNORE || key == K_NOP ) { 1255return -1 ;// get another key 1256 } 1257 1258disptick_T display_tick_saved = curwin -> w_display_tick ; 1259CommandLineState * s = (CommandLineState * )state ; 1260s -> c = key ; 1261 1262// If the cmdline was replaced externally (e.g. by setcmdline() 1263// during an <expr> mapping), clean up the wildmenu completion 1264// state to avoid using stale completion data. 1265if (ccline .cmdbuff_replaced && s -> xpc .xp_numfiles > 0 ) { 1266command_line_end_wildmenu (s , false,-1 ); 1267 } 1268ccline .cmdbuff_replaced = false; 1269 1270// Skip wildmenu during history navigation via Up/Down keys 1271if (s -> c == K_WILD && s -> did_hist_navigate ) { 1272s -> did_hist_navigate = false; 1273return 1 ; 1274 } 1275 1276if (s -> c == K_EVENT || s -> c == K_COMMAND || s -> c == K_LUA ) { 1277if (s -> c == K_EVENT ) { 1278state_handle_k_event (); 1279 }else if (s -> c == K_COMMAND ) { 1280do_cmdline (NULL ,getcmdkeycmd ,NULL ,DOCMD_NOWAIT ); 1281 }else { 1282map_execute_lua (false, false); 1283 } 1284// If the window changed incremental search state is not valid. 1285if (s -> is_state .winid != curwin -> handle ) { 1286init_incsearch_state (& s -> is_state ); 1287 } 1288// Re-apply 'incsearch' highlighting in case it was cleared. 1289if (curwin -> w_display_tick > display_tick_saved && s -> is_state .did_incsearch ) { 1290may_do_incsearch_highlighting (s -> firstc ,s -> count ,& s -> is_state ); 1291 } 1292// If f_setcmdline() changed the cmdline treat it as such. 1293if (ccline .cmdbuff_replaced ) { 1294command_line_changed (s ); 1295 } 1296 1297// nvim_select_popupmenu_item() can be called from the handling of 1298// K_EVENT, K_COMMAND, or K_LUA. 1299if (pum_want .active ) { 1300if (cmdline_pum_active ()) { 1301nextwild (& s -> xpc ,WILD_PUM_WANT ,0 ,s -> firstc != '@' ); 1302if (pum_want .finish ) { 1303nextwild (& s -> xpc ,WILD_APPLY ,WILD_NO_BEEP ,s -> firstc != '@' ); 1304command_line_end_wildmenu (s , false,s -> c ); 1305 } 1306 } 1307pum_want .active = false; 1308 } 1309 1310if (!cmdline_was_last_drawn ) { 1311redrawcmdline (); 1312 } 1313return 1 ; 1314 } 1315 1316if (KeyTyped ) { 1317s -> some_key_typed = true; 1318 1319if (cmdmsg_rl && !KeyStuffed ) { 1320// Invert horizontal movements and operations. Only when 1321// typed by the user directly, not when the result of a 1322// mapping. 1323switch (s -> c ) { 1324case K_RIGHT : 1325s -> c = K_LEFT ;break ; 1326case K_S_RIGHT : 1327s -> c = K_S_LEFT ;break ; 1328case K_C_RIGHT : 1329s -> c = K_C_LEFT ;break ; 1330case K_LEFT : 1331s -> c = K_RIGHT ;break ; 1332case K_S_LEFT : 1333s -> c = K_S_RIGHT ;break ; 1334case K_C_LEFT : 1335s -> c = K_C_RIGHT ;break ; 1336 } 1337 } 1338 } 1339 1340// Ignore got_int when CTRL-C was typed here. 1341// Don't ignore it in :global, we really need to break then, e.g., for 1342// ":g/pat/normal /pat" (without the <CR>). 1343// Don't ignore it for the input() function. 1344if ((s -> c == Ctrl_C ) 1345&& s -> firstc != '@' 1346&& !s -> break_ctrl_c 1347&& !global_busy ) { 1348got_int = false; 1349 } 1350 1351// free old command line when finished moving around in the history 1352// list 1353if (s -> lookfor != NULL 1354&& s -> c != K_S_DOWN && s -> c != K_S_UP 1355&& s -> c != K_DOWN && s -> c != K_UP 1356&& s -> c != K_PAGEDOWN && s -> c != K_PAGEUP 1357&& s -> c != K_KPAGEDOWN && s -> c != K_KPAGEUP 1358&& s -> c != K_LEFT && s -> c != K_RIGHT 1359&& (s -> xpc .xp_numfiles > 0 || (s -> c != Ctrl_P && s -> c != Ctrl_N ))) { 1360XFREE_CLEAR (s -> lookfor ); 1361s -> lookforlen = 0 ; 1362 } 1363 1364// When there are matching completions to select <S-Tab> works like 1365// CTRL-P (unless 'wc' is <S-Tab>). 1366if (s -> c != p_wc && s -> c == K_S_TAB && s -> xpc .xp_numfiles > 0 ) { 1367s -> c = Ctrl_P ; 1368 } 1369 1370if (p_wmnu ) { 1371s -> c = wildmenu_translate_key (& ccline ,s -> c ,& s -> xpc ,s -> did_wild_list ); 1372 } 1373 1374int wild_type = 0 ; 1375const bool key_is_wc = (s -> c == p_wc && KeyTyped )|| s -> c == p_wcm ; 1376if ((cmdline_pum_active ()|| wild_menu_showing || s -> did_wild_list ) 1377&& !key_is_wc && s -> xpc .xp_numfiles > 0 ) { 1378// Ctrl-Y: Accept the current selection and close the popup menu. 1379// Ctrl-E: cancel the cmdline popup menu and return the original text. 1380if (s -> c == Ctrl_E || s -> c == Ctrl_Y ) { 1381wild_type = (s -> c == Ctrl_E ) ?WILD_CANCEL :WILD_APPLY ; 1382nextwild (& s -> xpc ,wild_type ,WILD_NO_BEEP ,s -> firstc != '@' ); 1383 } 1384 } 1385 1386// Trigger CmdlineLeavePre autocommand 1387if ((KeyTyped && (s -> c == '\n' || s -> c == '\r' || s -> c == K_KENTER || s -> c == ESC )) 1388|| s -> c == Ctrl_C ) { 1389set_vim_var_char (s -> c );// Set v:char 1390trigger_cmd_autocmd (s -> cmdline_type ,EVENT_CMDLINELEAVEPRE ); 1391s -> event_cmdlineleavepre_triggered = true; 1392if ((s -> c == ESC || s -> c == Ctrl_C )&& (wim_flags [0 ]& kOptWimFlagList )) { 1393set_no_hlsearch (true); 1394 } 1395 } 1396 1397// The wildmenu is cleared if the pressed key is not used for 1398// navigating the wild menu (i.e. the key is not 'wildchar' or 1399// 'wildcharm' or Ctrl-N or Ctrl-P or Ctrl-A or Ctrl-L). 1400// If the popup menu is displayed, then PageDown and PageUp keys are 1401// also used to navigate the menu. 1402bool end_wildmenu = (!key_is_wc && s -> c != Ctrl_Z 1403&& s -> c != Ctrl_N && s -> c != Ctrl_P && s -> c != Ctrl_A 1404&& s -> c != Ctrl_L ); 1405end_wildmenu = end_wildmenu && (!cmdline_pum_active () 1406|| (s -> c != K_PAGEDOWN && s -> c != K_PAGEUP 1407&& s -> c != K_KPAGEDOWN && s -> c != K_KPAGEUP 1408&& s -> c != K_MOUSEDOWN && s -> c != K_MOUSEUP 1409&& s -> c != K_MOUSELEFT && s -> c != K_MOUSERIGHT )); 1410 1411// free expanded names when finished walking through matches 1412if (end_wildmenu ) { 1413command_line_end_wildmenu (s ,key_is_wc ,s -> c ); 1414 } 1415 1416if (p_wmnu ) { 1417s -> c = wildmenu_process_key (& ccline ,s -> c ,& s -> xpc ); 1418 } 1419 1420// CTRL-\ CTRL-N or CTRL-\ CTRL-G goes to Normal mode, 1421// CTRL-\ e prompts for an expression. 1422if (s -> c == Ctrl_BSL ) { 1423switch (command_line_handle_ctrl_bsl (s )) { 1424case CMDLINE_CHANGED : 1425return command_line_changed (s ); 1426case CMDLINE_NOT_CHANGED : 1427return command_line_not_changed (s ); 1428case GOTO_NORMAL_MODE : 1429return 0 ;// back to cmd mode 1430default : 1431s -> c = Ctrl_BSL ;// backslash key not processed by 1432// command_line_handle_ctrl_bsl() 1433 } 1434 } 1435 1436if (s -> c == cedit_key ) { 1437// c_CTRL-F: Open cmdwin. Return Ctrl_C so the current cmdline cancels; when the user 1438// confirms/cancels cmdwin, it will reopen cmdline with the command pre-filled. 1439if (ex_normal_busy == 0 && got_int == false) { 1440s -> c = open_cmdwin (); 1441s -> some_key_typed = true;// Treat c_CTRL-F as "typed" to skip the wait-return prompt. 1442 } 1443 }else { 1444s -> c = do_digraph (s -> c ); 1445 } 1446 1447if (s -> c == '\n' 1448|| s -> c == '\r' 1449|| s -> c == K_KENTER 1450|| (s -> c == ESC 1451&& (!KeyTyped || vim_strchr (p_cpo ,kCpoEsc )!= NULL ))) { 1452s -> gotesc = false;// Might have typed ESC previously, don't 1453// truncate the cmdline now. 1454if (ccheck_abbr (s -> c + ABBR_OFF )) { 1455return command_line_changed (s ); 1456 } 1457 1458if (!cmd_silent ) { 1459if (!ui_has (kUICmdline )) { 1460msg_cursor_goto (msg_row ,0 ); 1461 } 1462ui_flush (); 1463 } 1464return 0 ; 1465 } 1466 1467// Completion for 'wildchar', 'wildcharm', and wildtrigger() 1468if ((s -> c == p_wc && !s -> gotesc && KeyTyped )|| s -> c == p_wcm || s -> c == K_WILD 1469|| s -> c == Ctrl_Z ) { 1470if (s -> c == K_WILD ) { 1471emsg_silent ++ ;// Silence the bell 1472 } 1473int res = command_line_wildchar_complete (s ); 1474if (s -> c == K_WILD ) { 1475emsg_silent -- ; 1476 } 1477if (res == CMDLINE_CHANGED ) { 1478return command_line_changed (s ); 1479 } 1480if (s -> c == K_WILD ) { 1481return command_line_not_changed (s ); 1482 } 1483 } 1484 1485s -> gotesc = false; 1486 1487// <S-Tab> goes to last match, in a clumsy way 1488if (s -> c == K_S_TAB && KeyTyped ) { 1489if (nextwild (& s -> xpc ,WILD_EXPAND_KEEP ,0 ,s -> firstc != '@' )== OK ) { 1490if (s -> xpc .xp_numfiles > 1 1491&& ((!s -> did_wild_list && (wim_flags [s -> wim_index ]& kOptWimFlagList ))|| p_wmnu )) { 1492// Trigger the popup menu when wildoptions=pum 1493bool list = wim_flags [s -> wim_index ]& kOptWimFlagList ; 1494showmatches (& s -> xpc ,p_wmnu && !list ,list ,p_wmnu ?wim_flags [0 ] :0 ); 1495 } 1496nextwild (& s -> xpc ,WILD_PREV ,0 ,s -> firstc != '@' ); 1497nextwild (& s -> xpc ,WILD_PREV ,0 ,s -> firstc != '@' ); 1498return command_line_changed (s ); 1499 } 1500 } 1501 1502if (s -> c == NUL || s -> c == K_ZERO ) { 1503// NUL is stored as NL 1504s -> c = NL ; 1505 } 1506 1507s -> do_abbr = true;// default: check for abbreviation 1508 1509// If already used to cancel/accept wildmenu, don't process the key further. 1510if (wild_type == WILD_CANCEL || wild_type == WILD_APPLY ) { 1511// Apply search highlighting 1512if (s -> is_state .winid != curwin -> handle ) { 1513init_incsearch_state (& s -> is_state ); 1514 } 1515if (KeyTyped || vpeekc ()== NUL ) { 1516may_do_incsearch_highlighting (s -> firstc ,s -> count ,& s -> is_state ); 1517 } 1518return command_line_not_changed (s ); 1519 } 1520 1521return command_line_handle_key (s ); 1522} 1523 1524// May adjust 'incsearch' highlighting for typing CTRL-G and CTRL-T, go to next 1525// or previous match. 1526// Returns FAIL when calling command_line_not_changed. 1527static int may_do_command_line_next_incsearch (int firstc ,int count ,incsearch_state_T * s , 1528bool next_match ) 1529FUNC_ATTR_NONNULL_ALL 1530{ 1531int skiplen ,patlen ,search_delim ; 1532bool magic = p_magic ; 1533 1534// Parsing range may already set the last search pattern. 1535// NOTE: must call restore_last_search_pattern() before returning! 1536save_last_search_pattern (); 1537 1538if (!do_incsearch_highlighting (firstc ,& search_delim ,s ,& skiplen , 1539& patlen ,& magic )) { 1540restore_last_search_pattern (); 1541return OK ; 1542 } 1543if (patlen == 0 && ccline .cmdbuff [skiplen ]== NUL ) { 1544restore_last_search_pattern (); 1545return FAIL ; 1546 } 1547 1548ui_busy_start (); 1549ui_flush (); 1550 1551pos_T t ; 1552char * pat = ccline .cmdbuff + skiplen ; 1553char * dircp = NULL ; 1554char * searchstr = pat ; 1555char * strcopy = NULL ; 1556size_t searchstrlen = (size_t )patlen ; 1557SearchOffset offset ; 1558int search_flags = SEARCH_NOOF ; 1559size_t patlen_s = (size_t )(ccline .cmdlen - skiplen ); 1560 1561// do not search for the search end delimiter, 1562// unless it is part of the pattern 1563parse_search_pattern_offset (& pat ,& patlen_s ,search_delim ,SEARCH_OPT ,& strcopy ,& searchstr , 1564& searchstrlen ,& dircp ,& offset ); 1565 1566if (next_match ) { 1567t = s -> match_end ; 1568if (lt (s -> match_start ,s -> match_end )) { 1569// start searching at the end of the match 1570// not at the beginning of the next column 1571decl (& t ); 1572 } 1573search_flags += SEARCH_COL ; 1574 }else { 1575t = s -> match_start ; 1576 } 1577if (!p_hls ) { 1578search_flags += SEARCH_KEEP ; 1579 } 1580emsg_off ++ ; 1581int found = searchit (curwin ,curbuf ,& t ,NULL , 1582next_match ?FORWARD :BACKWARD , 1583searchstr ,searchstrlen ,count ,search_flags , 1584RE_SEARCH ,magic ,NULL ); 1585emsg_off -- ; 1586if (dircp != NULL ) { 1587* dircp = (char )search_delim ; 1588 } 1589ui_busy_stop (); 1590if (found ) { 1591pos_T match_start = s -> match_start ; 1592pos_T match_end = s -> match_end ; 1593int64_t off = offset .off ; 1594 1595s -> search_start = match_start ; 1596if (!offset .line && (offset .end || off != 0 )) { 1597if (offset .end ) { 1598s -> search_start = match_end ; 1599decl (& s -> search_start ); 1600 } 1601while (off > 0 ) { 1602if (incl (& s -> search_start )== -1 ) { 1603break ; 1604 } 1605off -- ; 1606 } 1607while (off < 0 ) { 1608if (decl (& s -> search_start )== -1 ) { 1609break ; 1610 } 1611off ++ ; 1612 } 1613 } 1614s -> match_end = t ; 1615s -> match_start = t ; 1616if (!next_match && firstc != '?' ) { 1617// move just before the current match, so that 1618// when nv_search finishes the cursor will be 1619// put back on the match 1620s -> search_start = t ; 1621decl (& s -> search_start ); 1622 }else if (next_match && firstc == '?' ) { 1623// move just after the current match, so that 1624// when nv_search finishes the cursor will be 1625// put back on the match 1626s -> search_start = t ; 1627incl (& s -> search_start ); 1628 } 1629if (lt (t ,s -> search_start )&& next_match ) { 1630// wrap around 1631s -> search_start = t ; 1632if (firstc == '?' ) { 1633incl (& s -> search_start ); 1634 }else { 1635decl (& s -> search_start ); 1636 } 1637 } 1638 1639set_search_match (& s -> match_end ); 1640curwin -> w_cursor = s -> match_start ; 1641changed_cline_bef_curs (curwin ); 1642update_topline (curwin ); 1643validate_cursor (curwin ); 1644Search .hl_match = true; 1645save_viewstate (curwin ,& s -> old_viewstate ); 1646redraw_later (curwin ,UPD_NOT_VALID ); 1647update_screen (); 1648Search .hl_match = false; 1649redrawcmdline (); 1650curwin -> w_cursor = s -> match_end ; 1651 }else { 1652vim_beep (kOptBoFlagError ); 1653 } 1654xfree (strcopy ); 1655restore_last_search_pattern (); 1656return FAIL ; 1657} 1658 1659/// Handle backspace, delete and CTRL-W keys in the command-line mode. 1660static int command_line_erase_chars (CommandLineState * s ) 1661{ 1662if (s -> c == K_KDEL ) { 1663s -> c = K_DEL ; 1664 } 1665 1666// Delete current character is the same as backspace on next 1667// character, except at end of line 1668if (s -> c == K_DEL && ccline .cmdpos != ccline .cmdlen ) { 1669ccline .cmdpos ++ ; 1670 } 1671if (s -> c == K_DEL ) { 1672ccline .cmdpos += mb_off_next (ccline .cmdbuff ,ccline .cmdbuff + ccline .cmdpos ); 1673 } 1674 1675if (ccline .cmdpos > 0 ) { 1676int j = ccline .cmdpos ; 1677char * p = mb_prevptr (ccline .cmdbuff ,ccline .cmdbuff + j ); 1678 1679if (s -> c == Ctrl_W ) { 1680while (p > ccline .cmdbuff && ascii_isspace (* p )) { 1681p = mb_prevptr (ccline .cmdbuff ,p ); 1682 } 1683 1684int i = mb_get_class (p ); 1685while (p > ccline .cmdbuff && mb_get_class (p )== i ) { 1686p = mb_prevptr (ccline .cmdbuff ,p ); 1687 } 1688 1689if (mb_get_class (p )!= i ) { 1690p += utfc_ptr2len (p ); 1691 } 1692 } 1693 1694ccline .cmdpos = (int )(p - ccline .cmdbuff ); 1695ccline .cmdlen -= j - ccline .cmdpos ; 1696int i = ccline .cmdpos ; 1697 1698while (i < ccline .cmdlen ) { 1699ccline .cmdbuff [i ++ ]= ccline .cmdbuff [j ++ ]; 1700 } 1701 1702// Truncate at the end, required for multi-byte chars. 1703ccline .cmdbuff [ccline .cmdlen ]= NUL ; 1704if (ccline .cmdlen == 0 ) { 1705s -> is_state .search_start = s -> is_state .save_cursor ; 1706// save view settings, so that the screen won't be restored at the 1707// wrong position 1708s -> is_state .old_viewstate = s -> is_state .init_viewstate ; 1709 } 1710redrawcmd (); 1711 }else if (ccline .cmdlen == 0 && s -> c != Ctrl_W 1712&& ccline .cmdprompt == NULL && s -> indent == 0 ) { 1713// In debug mode it doesn't make sense to return. 1714if (ccline .cmdfirstc == '>' ) { 1715return CMDLINE_NOT_CHANGED ; 1716 } 1717 1718dealloc_cmdbuff ();// no commandline to return 1719 1720if (!cmd_silent && !ui_has (kUICmdline )) { 1721msg_col = 0 ; 1722msg_putchar (' ' );// delete ':' 1723 } 1724s -> is_state .search_start = s -> is_state .save_cursor ; 1725redraw_cmdline = true; 1726return GOTO_NORMAL_MODE ; 1727 } 1728return CMDLINE_CHANGED ; 1729} 1730 1731/// Handle the CTRL-^ key in the command-line mode and toggle the use of the 1732/// language :lmap mappings and/or Input Method. 1733static void command_line_toggle_langmap (CommandLineState * s ) 1734{ 1735OptInt * b_im_ptr = buf_valid (s -> b_im_ptr_buf ) ?s -> b_im_ptr :NULL ; 1736if (map_to_exists_mode ("" ,MODE_LANGMAP , false)) { 1737// ":lmap" mappings exists, toggle use of mappings. 1738State ^=MODE_LANGMAP ; 1739if (b_im_ptr != NULL ) { 1740if (State & MODE_LANGMAP ) { 1741* b_im_ptr = B_IMODE_LMAP ; 1742 }else { 1743* b_im_ptr = B_IMODE_NONE ; 1744 } 1745 } 1746 } 1747 1748if (b_im_ptr != NULL ) { 1749if (b_im_ptr == & curbuf -> b_p_iminsert ) { 1750set_iminsert_global (curbuf ); 1751 }else { 1752set_imsearch_global (curbuf ); 1753 } 1754 } 1755ui_cursor_shape ();// may show different cursor shape 1756// Show/unshow value of 'keymap' in status lines later. 1757status_redraw_curbuf (); 1758} 1759 1760/// Handle the CTRL-R key in the command-line mode and insert the contents of a 1761/// numbered or named register. 1762static int command_line_insert_reg (CommandLineState * s ) 1763{ 1764const int save_new_cmdpos = new_cmdpos ; 1765 1766putcmdline ('"' , true); 1767no_mapping ++ ; 1768allow_keys ++ ; 1769int i = s -> c = plain_vgetc ();// CTRL-R <char> 1770if (i == Ctrl_O ) { 1771i = Ctrl_R ;// CTRL-R CTRL-O == CTRL-R CTRL-R 1772 } 1773 1774if (i == Ctrl_R ) { 1775s -> c = plain_vgetc ();// CTRL-R CTRL-R <char> 1776 } 1777no_mapping -- ; 1778allow_keys -- ; 1779// Insert the result of an expression. 1780new_cmdpos = -1 ; 1781if (s -> c == '=' ) { 1782if (ccline .cmdfirstc == '=' // can't do this recursively 1783|| cmdline_star > 0 ) {// or when typing a password 1784beep_flush (); 1785s -> c = ESC ; 1786 }else { 1787s -> c = get_expr_register (); 1788 } 1789 } 1790 1791bool literally = false; 1792if (s -> c != ESC ) {// use ESC to cancel inserting register 1793literally = i == Ctrl_R || is_literal_register (s -> c ); 1794cmdline_paste (s -> c ,literally , false); 1795 1796// When there was a serious error abort getting the 1797// command line. 1798if (aborting ()) { 1799s -> gotesc = true;// will free ccline.cmdbuff after 1800// putting it in history 1801return GOTO_NORMAL_MODE ; 1802 } 1803KeyTyped = false;// Don't do p_wc completion. 1804if (new_cmdpos >=0 ) { 1805// set_cmdline_pos() was used 1806ccline .cmdpos = MIN (ccline .cmdlen ,new_cmdpos ); 1807 } 1808 } 1809new_cmdpos = save_new_cmdpos ; 1810 1811// remove the double quote 1812ccline .special_char = NUL ; 1813redrawcmd (); 1814 1815// With "literally": the command line has already changed. 1816// Else: the text has been stuffed, but the command line didn't change yet. 1817return literally ?CMDLINE_CHANGED :CMDLINE_NOT_CHANGED ; 1818} 1819 1820/// Handle the Left and Right mouse clicks in the command-line mode. 1821static void command_line_left_right_mouse (CommandLineState * s ) 1822{ 1823if (s -> c == K_LEFTRELEASE || s -> c == K_RIGHTRELEASE ) { 1824s -> ignore_drag_release = true; 1825 }else { 1826s -> ignore_drag_release = false; 1827 } 1828 1829ccline .cmdspos = cmd_startcol (); 1830for (ccline .cmdpos = 0 ;ccline .cmdpos < ccline .cmdlen ; 1831ccline .cmdpos ++ ) { 1832int cells = cmdline_charsize (ccline .cmdpos ); 1833if (mouse_row <=cmdline_row + ccline .cmdspos /Columns 1834&& mouse_col < ccline .cmdspos %Columns + cells ) { 1835break ; 1836 } 1837 1838// Count ">" for double-wide char that doesn't fit. 1839correct_screencol (ccline .cmdpos ,cells ,& ccline .cmdspos ); 1840ccline .cmdpos += utfc_ptr2len (ccline .cmdbuff + ccline .cmdpos )- 1 ; 1841ccline .cmdspos += cells ; 1842 } 1843} 1844 1845static void command_line_next_histidx (CommandLineState * s ,bool next_match ) 1846{ 1847while (true) { 1848// one step backwards 1849if (!next_match ) { 1850if (s -> hiscnt == get_hislen ()) { 1851// first time 1852s -> hiscnt = * get_hisidx (s -> histype ); 1853 }else if (s -> hiscnt == 0 && * get_hisidx (s -> histype )!= get_hislen ()- 1 ) { 1854s -> hiscnt = get_hislen ()- 1 ; 1855 }else if (s -> hiscnt != * get_hisidx (s -> histype )+ 1 ) { 1856s -> hiscnt -- ; 1857 }else { 1858// at top of list 1859s -> hiscnt = s -> save_hiscnt ; 1860break ; 1861 } 1862 }else {// one step forwards 1863// on last entry, clear the line 1864if (s -> hiscnt == * get_hisidx (s -> histype )) { 1865s -> hiscnt = get_hislen (); 1866break ; 1867 } 1868 1869// not on a history line, nothing to do 1870if (s -> hiscnt == get_hislen ()) { 1871break ; 1872 } 1873 1874if (s -> hiscnt == get_hislen ()- 1 ) { 1875// wrap around 1876s -> hiscnt = 0 ; 1877 }else { 1878s -> hiscnt ++ ; 1879 } 1880 } 1881 1882if (s -> hiscnt < 0 || get_histentry (s -> histype )[s -> hiscnt ].hisstr == NULL ) { 1883s -> hiscnt = s -> save_hiscnt ; 1884break ; 1885 } 1886 1887if ((s -> c != K_UP && s -> c != K_DOWN ) 1888|| s -> hiscnt == s -> save_hiscnt 1889|| strncmp (get_histentry (s -> histype )[s -> hiscnt ].hisstr , 1890s -> lookfor , (size_t )s -> lookforlen )== 0 ) { 1891break ; 1892 } 1893 } 1894} 1895 1896/// Handle the Up, Down, Page Up, Page down, CTRL-N and CTRL-P key in the 1897/// command-line mode. 1898static int command_line_browse_history (CommandLineState * s ) 1899{ 1900if (s -> histype == HIST_INVALID || get_hislen ()== 0 || s -> firstc == NUL ) { 1901// no history 1902return CMDLINE_NOT_CHANGED ; 1903 } 1904 1905s -> save_hiscnt = s -> hiscnt ; 1906 1907// save current command string so it can be restored later 1908if (s -> lookfor == NULL ) { 1909s -> lookfor = xstrnsave (ccline .cmdbuff , (size_t )ccline .cmdlen ); 1910s -> lookfor [ccline .cmdpos ]= NUL ; 1911s -> lookforlen = ccline .cmdpos ; 1912 } 1913 1914bool next_match = (s -> c == K_DOWN || s -> c == K_S_DOWN || s -> c == Ctrl_N 1915|| s -> c == K_PAGEDOWN || s -> c == K_KPAGEDOWN ); 1916command_line_next_histidx (s ,next_match ); 1917 1918if (s -> hiscnt != s -> save_hiscnt ) {// jumped to other entry 1919char * p ; 1920int plen ; 1921int old_firstc ; 1922 1923dealloc_cmdbuff (); 1924 1925s -> xpc .xp_context = EXPAND_NOTHING ; 1926if (s -> hiscnt == get_hislen ()) { 1927p = s -> lookfor ;// back to the old one 1928plen = s -> lookforlen ; 1929 }else { 1930p = get_histentry (s -> histype )[s -> hiscnt ].hisstr ; 1931plen = (int )get_histentry (s -> histype )[s -> hiscnt ].hisstrlen ; 1932 } 1933 1934if (s -> histype == HIST_SEARCH 1935&& p != s -> lookfor 1936&& (old_firstc = (uint8_t )p [plen + 1 ])!= s -> firstc ) { 1937int len = 0 ; 1938// Correct for the separator character used when 1939// adding the history entry vs the one used now. 1940// First loop: count length. 1941// Second loop: copy the characters. 1942for (int i = 0 ;i <=1 ;i ++ ) { 1943len = 0 ; 1944for (int j = 0 ;p [j ]!= NUL ;j ++ ) { 1945// Replace old sep with new sep, unless it is 1946// escaped. 1947if (p [j ]== old_firstc 1948&& (j == 0 || p [j - 1 ]!= '\\' )) { 1949if (i > 0 ) { 1950ccline .cmdbuff [len ]= (char )s -> firstc ; 1951 } 1952 }else { 1953// Escape new sep, unless it is already 1954// escaped. 1955if (p [j ]== s -> firstc 1956&& (j == 0 || p [j - 1 ]!= '\\' )) { 1957if (i > 0 ) { 1958ccline .cmdbuff [len ]= '\\' ; 1959 } 1960len ++ ; 1961 } 1962 1963if (i > 0 ) { 1964ccline .cmdbuff [len ]= p [j ]; 1965 } 1966 } 1967len ++ ; 1968 } 1969 1970if (i == 0 ) { 1971alloc_cmdbuff (len ); 1972 } 1973 } 1974ccline .cmdbuff [len ]= NUL ; 1975ccline .cmdpos = ccline .cmdlen = len ; 1976 }else { 1977alloc_cmdbuff (plen ); 1978STRCPY (ccline .cmdbuff ,p ); 1979ccline .cmdpos = ccline .cmdlen = plen ; 1980 } 1981 1982redrawcmd (); 1983return CMDLINE_CHANGED ; 1984 } 1985beep_flush (); 1986return CMDLINE_NOT_CHANGED ; 1987} 1988 1989static int command_line_handle_key (CommandLineState * s ) 1990{ 1991// For one key prompt, avoid putting ESC and Ctrl_C onto cmdline. 1992// For all other keys, just put onto cmdline and exit. 1993if (ccline .one_key && s -> c != ESC && s -> c != Ctrl_C ) { 1994 gotoend ; 1995 } 1996 1997// Big switch for a typed command line character. 1998switch (s -> c ) { 1999case K_BS : 2000case Ctrl_H : 2001case K_DEL : 2002case K_KDEL : 2003case Ctrl_W : 2004switch (command_line_erase_chars (s )) { 2005case CMDLINE_NOT_CHANGED : 2006return command_line_not_changed (s ); 2007case GOTO_NORMAL_MODE : 2008return 0 ;// back to cmd mode 2009default : 2010return command_line_changed (s ); 2011 } 2012 2013case K_INS : 2014case K_KINS : 2015ccline .overstrike = !ccline .overstrike ; 2016ui_cursor_shape ();// may show different cursor shape 2017may_trigger_modechanged (); 2018status_redraw_curbuf (); 2019redraw_statuslines (); 2020return command_line_not_changed (s ); 2021 2022case Ctrl_HAT : 2023command_line_toggle_langmap (s ); 2024return command_line_not_changed (s ); 2025 2026case Ctrl_U : { 2027// delete all characters left of the cursor 2028int j = ccline .cmdpos ; 2029ccline .cmdlen -= j ; 2030int i = ccline .cmdpos = 0 ; 2031while (i < ccline .cmdlen ) { 2032ccline .cmdbuff [i ++ ]= ccline .cmdbuff [j ++ ]; 2033 } 2034 2035// Truncate at the end, required for multi-byte chars. 2036ccline .cmdbuff [ccline .cmdlen ]= NUL ; 2037if (ccline .cmdlen == 0 ) { 2038s -> is_state .search_start = s -> is_state .save_cursor ; 2039 } 2040redrawcmd (); 2041return command_line_changed (s ); 2042 } 2043 2044case ESC :// get here if p_wc != ESC or when ESC typed twice 2045case Ctrl_C : 2046// When the highlight callback is active <C-c> should interrupt only it. 2047if (getln_interrupted_highlight && s -> c == Ctrl_C ) { 2048getln_interrupted_highlight = false; 2049return command_line_not_changed (s ); 2050 } 2051 2052s -> gotesc = true;// will free ccline.cmdbuff after 2053// putting it in history 2054return 0 ;// back to cmd mode 2055 2056case Ctrl_R :// insert register 2057switch (command_line_insert_reg (s )) { 2058case GOTO_NORMAL_MODE : 2059return 0 ;// back to cmd mode 2060case CMDLINE_CHANGED : 2061return command_line_changed (s ); 2062default : 2063return command_line_not_changed (s ); 2064 } 2065 2066case Ctrl_D : 2067if (showmatches (& s -> xpc , false, true,p_wmnu ?wim_flags [0 ] :0 ) 2068== EXPAND_NOTHING ) { 2069break ;// Use ^D as normal char instead 2070 } 2071 2072redrawcmd (); 2073return 1 ;// don't do incremental search now 2074 2075case K_RIGHT : 2076case K_S_RIGHT : 2077case K_C_RIGHT : 2078do { 2079if (ccline .cmdpos >=ccline .cmdlen ) { 2080break ; 2081 } 2082 2083int cells = cmdline_charsize (ccline .cmdpos ); 2084if (KeyTyped && ccline .cmdspos + cells >=Columns * Rows ) { 2085break ; 2086 } 2087 2088ccline .cmdspos += cells ; 2089ccline .cmdpos += utfc_ptr2len (ccline .cmdbuff + ccline .cmdpos ); 2090 }while ((s -> c == K_S_RIGHT || s -> c == K_C_RIGHT 2091|| (mod_mask & (MOD_MASK_SHIFT |MOD_MASK_CTRL ))) 2092&& ccline .cmdbuff [ccline .cmdpos ]!= ' ' ); 2093ccline .cmdspos = cmd_screencol (ccline .cmdpos ); 2094return command_line_not_changed (s ); 2095 2096case K_LEFT : 2097case K_S_LEFT : 2098case K_C_LEFT : 2099if (ccline .cmdpos == 0 ) { 2100return command_line_not_changed (s ); 2101 } 2102do { 2103ccline .cmdpos -- ; 2104// Move to first byte of possibly multibyte char. 2105ccline .cmdpos -= utf_head_off (ccline .cmdbuff , 2106ccline .cmdbuff + ccline .cmdpos ); 2107ccline .cmdspos -= cmdline_charsize (ccline .cmdpos ); 2108 }while (ccline .cmdpos > 0 2109&& (s -> c == K_S_LEFT || s -> c == K_C_LEFT 2110|| (mod_mask & (MOD_MASK_SHIFT |MOD_MASK_CTRL ))) 2111&& ccline .cmdbuff [ccline .cmdpos - 1 ]!= ' ' ); 2112 2113ccline .cmdspos = cmd_screencol (ccline .cmdpos ); 2114if (ccline .special_char != NUL ) { 2115putcmdline (ccline .special_char ,ccline .special_shift ); 2116 } 2117 2118return command_line_not_changed (s ); 2119 2120case K_IGNORE : 2121// Ignore mouse event or open_cmdwin() result. 2122return command_line_not_changed (s ); 2123 2124case K_MIDDLEDRAG : 2125case K_MIDDLERELEASE : 2126return command_line_not_changed (s );// Ignore mouse 2127 2128case K_MIDDLEMOUSE : 2129cmdline_paste (eval_has_provider ("clipboard" , false) ?'*' :0 , true, true); 2130redrawcmd (); 2131return command_line_changed (s ); 2132 2133case K_LEFTDRAG : 2134case K_LEFTRELEASE : 2135case K_RIGHTDRAG : 2136case K_RIGHTRELEASE : 2137// Ignore drag and release events when the button-down wasn't 2138// seen before. 2139if (s -> ignore_drag_release ) { 2140return command_line_not_changed (s ); 2141 } 2142FALLTHROUGH ; 2143case K_LEFTMOUSE : 2144// Return on left click above number prompt 2145if (ccline .mouse_used && mouse_row < cmdline_row ) { 2146* ccline .mouse_used = true; 2147return 0 ; 2148 } 2149FALLTHROUGH ; 2150case K_RIGHTMOUSE : 2151command_line_left_right_mouse (s ); 2152return command_line_not_changed (s ); 2153 2154// Mouse scroll wheel: scroll the completion info popup when the mouse 2155// is on top of it, otherwise ignored here. 2156case K_MOUSEDOWN : 2157case K_MOUSEUP : 2158case K_MOUSELEFT : 2159case K_MOUSERIGHT : 2160if (cmdline_pum_active ()) { 2161cmdline_mousescroll (s -> c == K_MOUSEDOWN 2162 ?MSCR_DOWN 2163 : (s -> c == K_MOUSEUP 2164 ?MSCR_UP 2165 :s -> c == K_MOUSELEFT ?MSCR_LEFT :MSCR_RIGHT )); 2166 } 2167return command_line_not_changed (s ); 2168 2169// Alternate buttons ignored here 2170case K_X1MOUSE : 2171case K_X1DRAG : 2172case K_X1RELEASE : 2173case K_X2MOUSE : 2174case K_X2DRAG : 2175case K_X2RELEASE : 2176case K_MOUSEMOVE : 2177return command_line_not_changed (s ); 2178 2179case K_SELECT :// end of Select mode mapping - ignore 2180return command_line_not_changed (s ); 2181 2182case Ctrl_B :// begin of command line 2183case K_HOME : 2184case K_KHOME : 2185case K_S_HOME : 2186case K_C_HOME : 2187ccline .cmdpos = 0 ; 2188ccline .cmdspos = cmd_startcol (); 2189return command_line_not_changed (s ); 2190 2191case Ctrl_E :// end of command line 2192case K_END : 2193case K_KEND : 2194case K_S_END : 2195case K_C_END : 2196ccline .cmdpos = ccline .cmdlen ; 2197ccline .cmdspos = cmd_screencol (ccline .cmdpos ); 2198return command_line_not_changed (s ); 2199 2200case Ctrl_A :// all matches 2201if (cmdline_pum_active ()) { 2202// As Ctrl-A completes all the matches, close the popup 2203// menu (if present) 2204cmdline_pum_cleanup (& ccline ); 2205 } 2206 2207if (nextwild (& s -> xpc ,WILD_ALL ,0 ,s -> firstc != '@' )== FAIL ) { 2208break ; 2209 } 2210s -> xpc .xp_context = EXPAND_NOTHING ; 2211s -> did_wild_list = false; 2212return command_line_changed (s ); 2213 2214case Ctrl_L : 2215if (may_add_char_to_search (s -> firstc ,& s -> c ,& s -> is_state )== OK ) { 2216return command_line_not_changed (s ); 2217 } 2218 2219// completion: longest common part 2220if (nextwild (& s -> xpc ,WILD_LONGEST ,0 ,s -> firstc != '@' )== FAIL ) { 2221break ; 2222 } 2223return command_line_changed (s ); 2224 2225case Ctrl_N :// next match 2226case Ctrl_P :// previous match 2227if (s -> xpc .xp_numfiles > 0 ) { 2228const int wild_type = (s -> c == Ctrl_P ) ?WILD_PREV :WILD_NEXT ; 2229if (nextwild (& s -> xpc ,wild_type ,0 ,s -> firstc != '@' )== FAIL ) { 2230break ; 2231 } 2232return command_line_changed (s ); 2233 } 2234FALLTHROUGH ; 2235 2236case K_UP : 2237case K_DOWN : 2238case K_S_UP : 2239case K_S_DOWN : 2240case K_PAGEUP : 2241case K_KPAGEUP : 2242case K_PAGEDOWN : 2243case K_KPAGEDOWN : 2244if (cmdline_pum_active () 2245&& (s -> c == K_PAGEUP || s -> c == K_PAGEDOWN 2246|| s -> c == K_KPAGEUP || s -> c == K_KPAGEDOWN )) { 2247// If the popup menu is displayed, then PageUp and PageDown 2248// are used to scroll the menu. 2249const int wild_type = 2250 (s -> c == K_PAGEDOWN || s -> c == K_KPAGEDOWN ) ?WILD_PAGEDOWN :WILD_PAGEUP ; 2251if (nextwild (& s -> xpc ,wild_type ,0 ,s -> firstc != '@' )== FAIL ) { 2252break ; 2253 } 2254return command_line_changed (s ); 2255 }else { 2256switch (command_line_browse_history (s )) { 2257case CMDLINE_CHANGED : 2258s -> did_hist_navigate = true; 2259return command_line_changed (s ); 2260case GOTO_NORMAL_MODE : 2261return 0 ; 2262default : 2263return command_line_not_changed (s ); 2264 } 2265 } 2266 2267case Ctrl_G :// next match 2268case Ctrl_T :// previous match 2269if (may_do_command_line_next_incsearch (s -> firstc ,s -> count ,& s -> is_state , 2270s -> c == Ctrl_G )== FAIL ) { 2271return command_line_not_changed (s ); 2272 } 2273break ; 2274 2275case Ctrl_V : 2276case Ctrl_Q : 2277s -> ignore_drag_release = true; 2278putcmdline ('^' , true); 2279 2280// Get next (two) characters. 2281// Do not include modifiers into the key for CTRL-SHIFT-V. 2282s -> c = get_literal (mod_mask & MOD_MASK_SHIFT ); 2283 2284s -> do_abbr = false;// don't do abbreviation now 2285ccline .special_char = NUL ; 2286// may need to remove ^ when composing char was typed 2287if (utf_iscomposing_first (s -> c )&& !cmd_silent ) { 2288if (ui_has (kUICmdline )) { 2289// TODO(bfredl): why not make unputcmdline also work with true? 2290unputcmdline (); 2291 }else { 2292draw_cmdline (ccline .cmdpos ,ccline .cmdlen - ccline .cmdpos ); 2293msg_putchar (' ' ); 2294cursorcmd (); 2295 } 2296 } 2297break ; 2298 2299case Ctrl_K : 2300s -> ignore_drag_release = true; 2301putcmdline ('?' , true); 2302s -> c = get_digraph (true); 2303ccline .special_char = NUL ; 2304 2305if (s -> c != NUL ) { 2306break ; 2307 } 2308 2309redrawcmd (); 2310return command_line_not_changed (s ); 2311 2312case Ctrl__ :// CTRL-_: switch language mode 2313if (!p_ari ) { 2314break ; 2315 } 2316return command_line_not_changed (s ); 2317 2318case 'q' : 2319// Number prompts use the mouse and return on 'q' press 2320if (ccline .mouse_used ) { 2321* ccline .cmdbuff = NUL ; 2322return 0 ; 2323 } 2324FALLTHROUGH ; 2325 2326default : 2327// Normal character with no special meaning. Just set mod_mask 2328// to 0x0 so that typing Shift-Space in the GUI doesn't enter 2329// the string <S-Space>. This should only happen after ^V. 2330if (!IS_SPECIAL (s -> c )) { 2331mod_mask = 0x0 ; 2332 } 2333break ; 2334 } 2335 2336// End of switch on command line character. 2337// We come here if we have a normal character. 2338if (s -> do_abbr && (IS_SPECIAL (s -> c )|| !vim_iswordc (s -> c )) 2339// Add ABBR_OFF for characters above 0x100, this is 2340// what check_abbr() expects. 2341&& (ccheck_abbr ((s -> c >=0x100 ) ? (s -> c + ABBR_OFF ) :s -> c ) 2342|| s -> c == Ctrl_RSB )) { 2343return command_line_changed (s ); 2344 } 2345 2346end : 2347// put the character in the command line 2348if (IS_SPECIAL (s -> c )|| mod_mask != 0 ) { 2349put_on_cmdline (get_special_key_name (s -> c ,mod_mask ),-1 , true); 2350 }else { 2351int j = utf_char2bytes (s -> c ,IObuff ); 2352IObuff [j ]= NUL ;// exclude composing chars 2353put_on_cmdline (IObuff ,j , true); 2354 } 2355return ccline .one_key ?0 :command_line_changed (s ); 2356} 2357 2358/// Trigger CursorMovedC autocommands. 2359static void may_trigger_cursormovedc (CommandLineState * s ) 2360{ 2361if (ccline .cmdpos != s -> prev_cmdpos ) { 2362trigger_cmd_autocmd (s -> cmdline_type ,EVENT_CURSORMOVEDC ); 2363ccline .redraw_state = MAX (ccline .redraw_state ,kCmdRedrawPos ); 2364 } 2365} 2366 2367static int command_line_not_changed (CommandLineState * s ) 2368{ 2369may_trigger_cursormovedc (s ); 2370s -> prev_cmdpos = ccline .cmdpos ; 2371// Incremental searches for "/" and "?": 2372// Enter command_line_not_changed() when a character has been read but the 2373// command line did not change. Then we only search and redraw if something 2374// changed in the past. 2375// Enter command_line_changed() when the command line did change. 2376if (!s -> is_state .incsearch_postponed ) { 2377return 1 ; 2378 } 2379return command_line_changed (s ); 2380} 2381 2382/// Guess that the pattern matches everything. Only finds specific cases, such 2383/// as a trailing \|, which can happen while typing a pattern. 2384static bool empty_pattern (char * p ,size_t len ,int delim ) 2385{ 2386magic_T magic_val = MAGIC_ON ; 2387 2388if (len > 0 ) { 2389skip_regexp_ex (p ,delim ,p_magic ,NULL ,NULL ,& magic_val ); 2390 }else { 2391return true; 2392 } 2393 2394return empty_pattern_magic (p ,len ,magic_val ); 2395} 2396 2397static bool empty_pattern_magic (char * p ,size_t len ,magic_T magic_val ) 2398{ 2399// remove trailing \v and the like 2400while (len >=2 && p [len - 2 ]== '\\' 2401&& vim_strchr ("mMvVcCZ" , (uint8_t )p [len - 1 ])!= NULL ) { 2402len -= 2 ; 2403 } 2404 2405// true, if the pattern is empty, or the pattern ends with \| and magic is 2406// set (or it ends with '|' and very magic is set) 2407return len == 0 || (len > 1 && p [len - 1 ]== '|' 2408&& ((p [len - 2 ]== '\\' && magic_val == MAGIC_ON ) 2409|| (p [len - 2 ]!= '\\' && magic_val == MAGIC_ALL ))); 2410} 2411 2412handle_T cmdpreview_get_bufnr (void ) 2413{ 2414return cmdpreview_bufnr ; 2415} 2416 2417int cmdpreview_get_ns (void ) 2418{ 2419return cmdpreview_ns ; 2420} 2421 2422/// Sets up command preview buffer. 2423/// 2424/// @return Pointer to command preview buffer if succeeded, NULL if failed. 2425static buf_T * cmdpreview_open_buf (void ) 2426{ 2427buf_T * cmdpreview_buf = cmdpreview_bufnr ?buflist_findnr (cmdpreview_bufnr ) :NULL ; 2428 2429// If preview buffer doesn't exist, open one. 2430if (cmdpreview_buf == NULL ) { 2431Error err = ERROR_INIT ; 2432handle_T bufnr = nvim_create_buf (false, true,& err ); 2433 2434if (ERROR_SET (& err )) { 2435return NULL ; 2436 } 2437 2438cmdpreview_buf = buflist_findnr (bufnr ); 2439 } 2440 2441// Preview buffer cannot preview itself! 2442if (cmdpreview_buf == curbuf ) { 2443return NULL ; 2444 } 2445 2446// Rename preview buffer. 2447CtxSwitch aco = {0 }; 2448ctx_switch (& aco ,NULL ,NULL ,cmdpreview_buf ,kCtxKeepDirs ); 2449int retv = rename_buffer ("[Preview]" ); 2450ctx_restore (& aco ); 2451 2452if (retv == FAIL ) { 2453return NULL ; 2454 } 2455 2456// Temporarily switch to preview buffer to set it up for previewing. 2457ctx_switch (& aco ,NULL ,NULL ,cmdpreview_buf ,kCtxKeepDirs ); 2458buf_clear (); 2459curbuf -> b_p_ma = true; 2460curbuf -> b_p_ul = -1 ; 2461curbuf -> b_p_tw = 0 ;// Reset 'textwidth' (was set by ftplugin) 2462ctx_restore (& aco ); 2463cmdpreview_bufnr = cmdpreview_buf -> handle ; 2464 2465return cmdpreview_buf ; 2466} 2467 2468/// Open command preview window if it's not already open. 2469/// Returns to original window after opening command preview window. 2470/// 2471/// @param cmdpreview_buf Pointer to command preview buffer 2472/// 2473/// @return Pointer to command preview window if succeeded, NULL if failed. 2474static win_T * cmdpreview_open_win (buf_T * cmdpreview_buf ) 2475FUNC_ATTR_NONNULL_ALL 2476{ 2477win_T * save_curwin = curwin ; 2478 2479// Open preview window. 2480if (win_split ((int )p_cwh ,WSP_BOT )== FAIL ) { 2481return NULL ; 2482 } 2483 2484win_T * preview_win = curwin ; 2485Error err = ERROR_INIT ; 2486int result = OK ; 2487 2488// Switch to preview buffer 2489TRY_WRAP (& err , { 2490result = do_buffer (DOBUF_GOTO ,DOBUF_FIRST ,FORWARD ,cmdpreview_buf -> handle ,0 ); 2491 }); 2492if (ERROR_SET (& err )|| result == FAIL ) { 2493api_clear_error (& err ); 2494return NULL ; 2495 } 2496 2497curwin -> w_p_cul = false; 2498curwin -> w_p_cuc = false; 2499curwin -> w_p_spell = false; 2500curwin -> w_p_fen = false; 2501 2502win_enter (save_curwin , false); 2503return preview_win ; 2504} 2505 2506/// Closes any open command preview windows. 2507static void cmdpreview_close_win (void ) 2508{ 2509buf_T * buf = cmdpreview_bufnr ?buflist_findnr (cmdpreview_bufnr ) :NULL ; 2510if (buf != NULL ) { 2511close_windows (buf , false); 2512 } 2513} 2514 2515/// Save current state and prepare windows and buffers for command preview. 2516static void cmdpreview_prepare (CpInfo * cpinfo ) 2517FUNC_ATTR_NONNULL_ALL 2518{ 2519Set (ptr_t )saved_bufs = SET_INIT ; 2520 2521kv_init (cpinfo -> buf_info ); 2522kv_init (cpinfo -> win_info ); 2523 2524FOR_ALL_WINDOWS_IN_TAB (win ,curtab ) { 2525buf_T * buf = win -> w_buffer ; 2526 2527// Don't save state of command preview buffer or preview window. 2528if (buf -> handle == cmdpreview_bufnr ) { 2529continue ; 2530 } 2531 2532if (!set_has (ptr_t ,& saved_bufs ,buf )) { 2533CpBufInfo cp_bufinfo ; 2534cp_bufinfo .buf = buf ; 2535cp_bufinfo .save_b_p_ma = buf -> b_p_ma ; 2536cp_bufinfo .save_b_changed = buf -> b_changed ; 2537cp_bufinfo .save_b_op_start = buf -> b_op_start ; 2538cp_bufinfo .save_b_op_end = buf -> b_op_end ; 2539u_checkpoint (& cp_bufinfo .undo_checkpoint ,buf ); 2540kv_push (cpinfo -> buf_info ,cp_bufinfo ); 2541set_put (ptr_t ,& saved_bufs ,buf ); 2542 } 2543 2544CpWinInfo cp_wininfo ; 2545cp_wininfo .win = win ; 2546 2547// Save window cursor position and viewstate 2548cp_wininfo .save_w_cursor = win -> w_cursor ; 2549save_viewstate (win ,& cp_wininfo .save_viewstate ); 2550 2551// Save 'cursorline' and 'cursorcolumn' 2552cp_wininfo .save_w_p_cul = win -> w_p_cul ; 2553cp_wininfo .save_w_p_cuc = win -> w_p_cuc ; 2554 2555kv_push (cpinfo -> win_info ,cp_wininfo ); 2556 2557win -> w_p_cul = false;// Disable 'cursorline' so it doesn't mess up the highlights 2558win -> w_p_cuc = false;// Disable 'cursorcolumn' so it doesn't mess up the highlights 2559 } 2560 2561set_destroy (ptr_t ,& saved_bufs ); 2562 2563cpinfo -> save_hls = p_hls ; 2564cpinfo -> save_cmdmod = cmdmod ; 2565win_size_save (& cpinfo -> save_view ); 2566save_search_patterns (); 2567 2568p_hls = false;// Don't show search highlighting during live substitution 2569cmdmod .cmod_split = 0 ;// Disable :leftabove/botright modifiers 2570cmdmod .cmod_tab = 0 ;// Disable :tab modifier 2571cmdmod .cmod_flags |=CMOD_NOSWAPFILE ;// Disable swap for preview buffer 2572 2573u_sync (true); 2574} 2575 2576/// Restore the state of buffers and windows for command preview. 2577static void cmdpreview_restore_state (CpInfo * cpinfo ) 2578FUNC_ATTR_NONNULL_ALL 2579{ 2580for (size_t i = 0 ;i < cpinfo -> buf_info .size ;i ++ ) { 2581CpBufInfo cp_bufinfo = cpinfo -> buf_info .items [i ]; 2582buf_T * buf = cp_bufinfo .buf ; 2583 2584buf -> b_changed = cp_bufinfo .save_b_changed ; 2585 2586// Clear preview highlights. 2587extmark_clear (buf , (uint32_t )cmdpreview_ns ,0 ,0 ,MAXLNUM ,MAXCOL ); 2588 2589u_rollback (& cp_bufinfo .undo_checkpoint ,buf ); 2590 2591buf -> b_op_start = cp_bufinfo .save_b_op_start ; 2592buf -> b_op_end = cp_bufinfo .save_b_op_end ; 2593 2594buf -> b_p_ma = cp_bufinfo .save_b_p_ma ;// Restore 'modifiable' 2595 } 2596 2597for (size_t i = 0 ;i < cpinfo -> win_info .size ;i ++ ) { 2598CpWinInfo cp_wininfo = cpinfo -> win_info .items [i ]; 2599win_T * win = cp_wininfo .win ; 2600 2601// Restore window cursor position and viewstate 2602win -> w_cursor = cp_wininfo .save_w_cursor ; 2603restore_viewstate (win ,& cp_wininfo .save_viewstate ); 2604 2605// Restore 'cursorline' and 'cursorcolumn' 2606win -> w_p_cul = cp_wininfo .save_w_p_cul ; 2607win -> w_p_cuc = cp_wininfo .save_w_p_cuc ; 2608 2609update_topline (win ); 2610 } 2611 2612cmdmod = cpinfo -> save_cmdmod ;// Restore cmdmod 2613p_hls = cpinfo -> save_hls ;// Restore 'hlsearch' 2614restore_search_patterns ();// Restore search patterns 2615win_size_restore (& cpinfo -> save_view );// Restore window sizes 2616 2617ga_clear (& cpinfo -> save_view ); 2618kv_destroy (cpinfo -> win_info ); 2619kv_destroy (cpinfo -> buf_info ); 2620} 2621 2622/// Show 'inccommand' preview if command is previewable. It works like this: 2623/// 1. Store current undo information so we can revert to current state later. 2624/// 2. Execute the preview callback with the parsed command, preview buffer number and preview 2625/// namespace number as arguments. The preview callback sets the highlight and does the 2626/// changes required for the preview if needed. 2627/// 3. Preview callback returns 0, 1 or 2. 0 means no preview is shown. 1 means preview is shown 2628/// but preview window doesn't need to be opened. 2 means preview is shown and preview window 2629/// needs to be opened if inccommand=split. 2630/// 4. Use the return value of the preview callback to determine whether to 2631/// open the preview window or not and open preview window if needed. 2632/// 5. If the return value of the preview callback is not 0, update the screen while the effects 2633/// of the preview are still in place. 2634/// 6. Revert all changes made by the preview callback. 2635/// 2636/// @return whether preview is shown or not. 2637static bool cmdpreview_may_show (CommandLineState * s ) 2638{ 2639// Parse the command line and return if it fails. 2640exarg_T ea ; 2641cmdmod_T cmod ; 2642// Copy the command line so we can modify it. 2643int cmdpreview_type = 0 ; 2644char * cmdline = xstrdup (ccline .cmdbuff ); 2645const char * errormsg = NULL ; 2646emsg_off ++ ;// Block errors when parsing the command line, and don't update v:errmsg 2647if (!parse_cmdline (& cmdline ,& ea ,& cmod ,& errormsg , false)) { 2648emsg_off -- ; 2649 gotoend ; 2650 } 2651emsg_off -- ; 2652 2653// Check if command is previewable, if not, don't attempt to show preview 2654if (!(ea .argt & EX_PREVIEW )) { 2655undo_cmdmod (& cmod ); 2656 gotoend ; 2657 } 2658 2659// Cursor may be at the end of the message grid rather than at cmdspos. 2660// Place it there in case preview callback flushes it. #30696 2661cursorcmd (); 2662// Flush now: external cmdline may itself wish to update the screen which is 2663// currently disallowed during cmdpreview (no longer needed in case that changes). 2664cmdline_ui_flush (); 2665 2666// Swap invalid command range if needed 2667if ((ea .argt & EX_RANGE )&& ea .line1 > ea .line2 ) { 2668linenr_T lnum = ea .line1 ; 2669ea .line1 = ea .line2 ; 2670ea .line2 = lnum ; 2671 } 2672 2673CpInfo cpinfo ; 2674bool icm_split = * p_icm == 's' ;// inccommand=split 2675buf_T * cmdpreview_buf = NULL ; 2676win_T * cmdpreview_win = NULL ; 2677 2678emsg_silent ++ ;// Block error reporting as the command may be incomplete, 2679// but still update v:errmsg 2680msg_silent ++ ;// Block messages, namely ones that prompt 2681block_autocmds ();// Block events 2682 2683// Save current state and prepare for command preview. 2684cmdpreview_prepare (& cpinfo ); 2685 2686// Open preview buffer if inccommand=split. 2687if (icm_split && (cmdpreview_buf = cmdpreview_open_buf ())== NULL ) { 2688// Failed to create preview buffer, so disable preview. 2689set_option_direct (kOptInccommand ,STATIC_CSTR_AS_OBJ ("nosplit" ),0 ,SID_NONE ); 2690icm_split = false; 2691 } 2692// Setup preview namespace if it's not already set. 2693if (!cmdpreview_ns ) { 2694cmdpreview_ns = (int )nvim_create_namespace ((String )STRING_INIT ); 2695 } 2696 2697// Set cmdpreview state. 2698cmdpreview = true; 2699 2700// Execute the preview callback and use its return value to determine whether to show preview or 2701// open the preview window. The preview callback also handles doing the changes and highlights for 2702// the preview. 2703Error err = ERROR_INIT ; 2704TRY_WRAP (& err , { 2705cmdpreview_type = execute_cmd (& ea ,& cmod , true); 2706 }); 2707if (ERROR_SET (& err )) { 2708api_clear_error (& err ); 2709cmdpreview_type = 0 ; 2710 } 2711 2712// If inccommand=split and preview callback returns 2, open preview window. 2713if (icm_split && cmdpreview_type == 2 2714&& (cmdpreview_win = cmdpreview_open_win (cmdpreview_buf ))== NULL ) { 2715// If there's not enough room to open the preview window, just preview without the window. 2716cmdpreview_type = 1 ; 2717 } 2718 2719// If preview callback return value is nonzero, update screen now. 2720if (cmdpreview_type != 0 ) { 2721int save_rd = RedrawingDisabled ; 2722RedrawingDisabled = 0 ; 2723update_screen (); 2724RedrawingDisabled = save_rd ; 2725 } 2726 2727// Close preview window if it's open. 2728if (icm_split && cmdpreview_type == 2 && cmdpreview_win != NULL ) { 2729cmdpreview_close_win (); 2730 } 2731 2732// Restore state. 2733cmdpreview_restore_state (& cpinfo ); 2734 2735unblock_autocmds ();// Unblock events 2736msg_silent -- ;// Unblock messages 2737emsg_silent -- ;// Unblock error reporting 2738redrawcmdline (); 2739end : 2740xfree (cmdline ); 2741return cmdpreview_type != 0 ; 2742} 2743 2744/// Trigger CmdlineChanged autocommands. 2745static void do_autocmd_cmdlinechanged (int firstc ) 2746{ 2747if (has_event (EVENT_CMDLINECHANGED )) { 2748Error err = ERROR_INIT ; 2749save_v_event_T save_v_event ; 2750dict_T * dict = get_v_event (& save_v_event ); 2751 2752char firstcbuf [2 ]; 2753firstcbuf [0 ]= (char )firstc ; 2754firstcbuf [1 ]= 0 ; 2755 2756// set v:event to a dictionary with information about the commandline 2757tv_dict_add_str (dict ,S_LEN ("cmdtype" ),firstcbuf ); 2758tv_dict_add_nr (dict ,S_LEN ("cmdlevel" ),ccline .level ); 2759tv_dict_set_keys_readonly (dict ); 2760TRY_WRAP (& err , { 2761apply_autocmds (EVENT_CMDLINECHANGED ,firstcbuf ,firstcbuf , false,curbuf ); 2762restore_v_event (dict ,& save_v_event ); 2763 }); 2764if (ERROR_SET (& err )) { 2765if (!ui_has (kUIMessages )) { 2766msg_putchar ('\n' ); 2767 } 2768msg_scroll = true; 2769msg_puts_hl (err .msg ,HLF_E , true); 2770api_clear_error (& err ); 2771redrawcmd (); 2772 } 2773 } 2774} 2775 2776static int command_line_changed (CommandLineState * s ) 2777{ 2778const bool prev_cmdpreview = cmdpreview ; 2779if (s -> firstc == ':' 2780&& current_sctx .sc_sid == 0 // only if interactive 2781&& * p_icm != NUL // 'inccommand' is set 2782&& cmdline_star == 0 // not typing a password 2783&& !vpeekc_any () 2784&& cmdpreview_may_show (s )) { 2785// 'inccommand' preview has been shown. 2786 }else { 2787cmdpreview = false; 2788if (prev_cmdpreview ) { 2789// TODO(bfredl): add an immediate redraw flag for cmdline mode which will trigger 2790// at next wait-for-input 2791update_screen ();// Clear 'inccommand' preview. 2792 } 2793if (s -> xpc .xp_context == EXPAND_NOTHING && (KeyTyped || vpeekc ()== NUL )) { 2794may_do_incsearch_highlighting (s -> firstc ,s -> count ,& s -> is_state ); 2795 } 2796 } 2797 2798if (!ccline .cmdbuff_replaced 2799&& (ccline .cmdpos != s -> prev_cmdpos 2800|| (s -> prev_cmdbuff != NULL && strcmp (s -> prev_cmdbuff ,ccline .cmdbuff )!= 0 ))) { 2801// Trigger CmdlineChanged autocommands. 2802do_autocmd_cmdlinechanged (s -> firstc > 0 ?s -> firstc :'-' ); 2803 } 2804 2805may_trigger_cursormovedc (s ); 2806 2807if (p_arshape && !p_tbidi ) { 2808// Always redraw the whole command line to fix shaping and 2809// right-left typing. Not efficient, but it works. 2810// Do it only when there are no characters left to read 2811// to avoid useless intermediate redraws. 2812// if cmdline is external the ui handles shaping, no redraw needed. 2813if (!ui_has (kUICmdline )&& vpeekc ()== NUL ) { 2814redrawcmd (); 2815 } 2816 } 2817 2818return 1 ; 2819} 2820 2821/// Abandon the command line. 2822static void abandon_cmdline (void ) 2823{ 2824dealloc_cmdbuff (); 2825if (msg_scrolled == 0 ) { 2826compute_cmdrow (); 2827 } 2828// Avoid overwriting key prompt 2829if (!ccline .one_key ) { 2830msg ("" ,0 ); 2831redraw_cmdline = true; 2832 } 2833} 2834 2835/// getcmdline() - accept a command line starting with firstc. 2836/// 2837/// firstc == ':' get ":" command line. 2838/// firstc == '/' or '?' get search pattern 2839/// firstc == '=' get expression 2840/// firstc == '@' get text for input() function 2841/// firstc == '>' get text for debug mode 2842/// firstc == NUL get text for :insert command 2843/// firstc == -1 like NUL, and break on CTRL-C 2844/// 2845/// The line is collected in ccline.cmdbuff, which is reallocated to fit the 2846/// command line. 2847/// 2848/// Careful: getcmdline() can be called recursively! 2849/// 2850/// Return pointer to allocated string if there is a commandline, NULL 2851/// otherwise. 2852/// 2853/// @param count only used for incremental search 2854/// @param indent indent for inside conditionals 2855char * getcmdline (int firstc ,int count ,int indent ,bool do_concat FUNC_ATTR_UNUSED ) 2856{ 2857return (char * )command_line_enter (firstc ,count ,indent , true); 2858} 2859 2860/// Get a command line with a prompt 2861/// 2862/// This is prepared to be called recursively from getcmdline() (e.g. by 2863/// f_input() when evaluating an expression from `<C-r>=`). 2864/// 2865/// @param[in] firstc Prompt type: e.g. '@' for input(), '>' for debug. 2866/// @param[in] prompt Prompt string: what is displayed before the user text. 2867/// @param[in] hl_id Prompt highlight id. 2868/// @param[in] xp_context Type of expansion. 2869/// @param[in] xp_arg User-defined expansion argument. 2870/// @param[in] highlight_callback Callback used for highlighting user input. 2871/// @param[in] one_key Return after one key press for button prompt. 2872/// @param[in] mouse_used Set to true when returning after right mouse click. 2873/// 2874/// @return [allocated] Command line or NULL. 2875char * getcmdline_prompt (const int firstc ,const char * const prompt ,const int hl_id , 2876const int xp_context ,const char * const xp_arg , 2877const Callback highlight_callback ,bool one_key ,bool * mouse_used ) 2878FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_MALLOC 2879{ 2880const int msg_col_save = msg_col ; 2881 2882CmdlineInfo save_ccline ; 2883bool did_save_ccline = false; 2884if (ccline .cmdbuff != NULL ) { 2885// Save the values of the current cmdline and restore them below. 2886save_cmdline (& save_ccline ); 2887did_save_ccline = true; 2888 }else { 2889CLEAR_FIELD (ccline ); 2890 } 2891ccline .prompt_id = last_prompt_id ++ ; 2892ccline .cmdprompt = (char * )prompt ; 2893ccline .hl_id = hl_id ; 2894ccline .xp_context = xp_context ; 2895ccline .xp_arg = (char * )xp_arg ; 2896ccline .input_fn = (firstc == '@' ); 2897ccline .highlight_callback = highlight_callback ; 2898ccline .one_key = one_key ; 2899ccline .mouse_used = mouse_used ; 2900 2901const bool cmd_silent_saved = cmd_silent ; 2902int msg_silent_saved = msg_silent ; 2903msg_silent = 0 ; 2904cmd_silent = false;// Want to see the prompt. 2905 2906char * const ret = (char * )command_line_enter (firstc ,1 ,0 , false); 2907ccline .redraw_state = kCmdRedrawNone ; 2908 2909if (did_save_ccline ) { 2910restore_cmdline (& save_ccline ); 2911 } 2912msg_silent = msg_silent_saved ; 2913cmd_silent = cmd_silent_saved ; 2914// Restore msg_col, the prompt from input() may have changed it. 2915// But only if called recursively and the commandline is therefore being 2916// restored to an old one; if not, the input() prompt stays on the screen, 2917// so we need its modified msg_col left intact. 2918if (ccline .cmdbuff != NULL ) { 2919msg_col = msg_col_save ; 2920 } 2921 2922return ret ; 2923} 2924 2925/// Read the 'wildmode' option, fill wim_flags[]. 2926int check_opt_wim (void ) 2927{ 2928uint8_t new_wim_flags [4 ]; 2929int i ; 2930int idx = 0 ; 2931 2932for (i = 0 ;i < 4 ;i ++ ) { 2933new_wim_flags [i ]= 0 ; 2934 } 2935 2936for (char * p = p_wim ;* p ;p ++ ) { 2937// Note: Keep this in sync with opt_wim_values. 2938for (i = 0 ;ASCII_ISALPHA (p [i ]);i ++ ) {} 2939if (p [i ]!= NUL && p [i ]!= ',' && p [i ]!= ':' ) { 2940return FAIL ; 2941 } 2942if (i == 7 && strncmp (p ,"longest" ,7 )== 0 ) { 2943new_wim_flags [idx ] |=kOptWimFlagLongest ; 2944 }else if (i == 4 && strncmp (p ,"full" ,4 )== 0 ) { 2945new_wim_flags [idx ] |=kOptWimFlagFull ; 2946 }else if (i == 4 && strncmp (p ,"list" ,4 )== 0 ) { 2947new_wim_flags [idx ] |=kOptWimFlagList ; 2948 }else if (i == 8 && strncmp (p ,"lastused" ,8 )== 0 ) { 2949new_wim_flags [idx ] |=kOptWimFlagLastused ; 2950 }else if (i == 8 && strncmp (p ,"noselect" ,8 )== 0 ) { 2951new_wim_flags [idx ] |=kOptWimFlagNoselect ; 2952 }else if (i == 8 && strncmp (p ,"noinsert" ,8 )== 0 ) { 2953new_wim_flags [idx ] |=kOptWimFlagNoinsert ; 2954 }else { 2955return FAIL ; 2956 } 2957p += i ; 2958if (* p == NUL ) { 2959break ; 2960 } 2961if (* p == ',' ) { 2962if (idx == 3 ) { 2963return FAIL ; 2964 } 2965idx ++ ; 2966 } 2967 } 2968 2969// fill remaining entries with last flag 2970while (idx < 3 ) { 2971new_wim_flags [idx + 1 ]= new_wim_flags [idx ]; 2972idx ++ ; 2973 } 2974 2975// only when there are no errors, wim_flags[] is changed 2976for (i = 0 ;i < 4 ;i ++ ) { 2977wim_flags [i ]= new_wim_flags [i ]; 2978 } 2979return OK ; 2980} 2981 2982/// Return true when the text must not be changed and we can't switch to 2983/// another window or buffer. True when editing the command line etc. 2984bool text_locked (void ) 2985{ 2986if (expr_map_locked ()) { 2987return true; 2988 } 2989return textlock != 0 ; 2990} 2991 2992// Give an error message for a command that isn't allowed while the cmdline 2993// window is open or editing the cmdline in another way. 2994void text_locked_msg (void ) 2995{ 2996emsg (_ (get_text_locked_msg ())); 2997} 2998 2999const char * get_text_locked_msg (void ) 3000{ 3001return e_textlock ; 3002} 3003 3004/// Check for text, window or buffer locked. 3005/// Give an error message and return true if something is locked. 3006bool text_or_buf_locked (void ) 3007{ 3008if (text_locked ()) { 3009text_locked_msg (); 3010return true; 3011 } 3012return curbuf_locked (); 3013} 3014 3015/// Check if "curbuf->b_ro_locked" or "allbuf_lock" is set and 3016/// return true when it is and give an error message. 3017bool curbuf_locked (void ) 3018{ 3019if (curbuf -> b_ro_locked > 0 ) { 3020emsg (_ (e_cannot_edit_other_buf )); 3021return true; 3022 } 3023return allbuf_locked (); 3024} 3025 3026// Check if "allbuf_lock" is set and return true when it is and give an error 3027// message. 3028bool allbuf_locked (void ) 3029{ 3030if (allbuf_lock > 0 ) { 3031emsg (_ ("E811: Not allowed to change buffer information now" )); 3032return true; 3033 } 3034return false; 3035} 3036 3037static int cmdline_charsize (int idx ) 3038{ 3039if (cmdline_star > 0 ) {// showing '*', always 1 position 3040return 1 ; 3041 } 3042return ptr2cells (ccline .cmdbuff + idx ); 3043} 3044 3045/// Compute the offset of the cursor on the command line for the prompt and 3046/// indent. 3047static int cmd_startcol (void ) 3048{ 3049return ccline .cmdindent + ((ccline .cmdfirstc != NUL ) ?1 :0 ); 3050} 3051 3052/// Compute the column position for a byte position on the command line. 3053int cmd_screencol (int bytepos ) 3054{ 3055int m ;// maximum column 3056int col = cmd_startcol (); 3057if (KeyTyped ) { 3058m = cmdline_win ?cmdline_win -> w_view_width * cmdline_win -> w_view_height :Columns * Rows ; 3059if (m < 0 ) {// overflow, Columns or Rows at weird value 3060m = MAXCOL ; 3061 } 3062 }else { 3063m = MAXCOL ; 3064 } 3065 3066for (int i = 0 ;i < ccline .cmdlen && i < bytepos ; 3067i += utfc_ptr2len (ccline .cmdbuff + i )) { 3068int c = cmdline_charsize (i ); 3069// Count ">" for double-wide multi-byte char that doesn't fit. 3070correct_screencol (i ,c ,& col ); 3071 3072// If the cmdline doesn't fit, show cursor on last visible char. 3073// Don't move the cursor itself, so we can still append. 3074if ((col += c ) >=m ) { 3075col -= c ; 3076break ; 3077 } 3078 } 3079return col ; 3080} 3081 3082/// Check if the character at "idx", which is "cells" wide, is a multi-byte 3083/// character that doesn't fit, so that a ">" must be displayed. 3084static void correct_screencol (int idx ,int cells ,int * col ) 3085{ 3086if (utfc_ptr2len (ccline .cmdbuff + idx )> 1 3087&& utf_ptr2cells (ccline .cmdbuff + idx )> 1 3088&& (* col ) %Columns + cells > Columns ) { 3089 (* col )++ ; 3090 } 3091} 3092 3093/// Get an Ex command line for the ":" command. 3094/// 3095/// @param c normally ':', NUL for ":append" 3096/// @param indent indent for inside conditionals 3097char * getexline (int c ,void * cookie ,int indent ,bool do_concat ) 3098{ 3099// When executing a register, remove ':' that's in front of each line. 3100if (exec_from_reg && vpeekc ()== ':' ) { 3101vgetc (); 3102 } 3103 3104return getcmdline (c ,1 ,indent ,do_concat ); 3105} 3106 3107bool cmdline_overstrike (void ) 3108FUNC_ATTR_PURE 3109{ 3110return ccline .overstrike ; 3111} 3112 3113/// Return true if the cursor is at the end of the cmdline. 3114bool cmdline_at_end (void ) 3115FUNC_ATTR_PURE 3116{ 3117return (ccline .cmdpos >=ccline .cmdlen ); 3118} 3119 3120/// Deallocate a command line buffer, updating the buffer size and length. 3121static void dealloc_cmdbuff (void ) 3122{ 3123XFREE_CLEAR (ccline .cmdbuff ); 3124ccline .cmdlen = ccline .cmdbufflen = 0 ; 3125} 3126 3127/// Allocate a new command line buffer. 3128/// Assigns the new buffer to ccline.cmdbuff and ccline.cmdbufflen. 3129static void alloc_cmdbuff (int len ) 3130{ 3131// give some extra space to avoid having to allocate all the time 3132if (len < 80 ) { 3133len = 100 ; 3134 }else { 3135len += 20 ; 3136 } 3137 3138ccline .cmdbuff = xmalloc ((size_t )len ); 3139ccline .cmdbufflen = len ; 3140} 3141 3142/// Re-allocate the command line to length len + something extra. 3143void realloc_cmdbuff (int len ) 3144{ 3145if (len < ccline .cmdbufflen ) { 3146return ;// no need to resize 3147 } 3148 3149char * p = ccline .cmdbuff ; 3150 3151alloc_cmdbuff (len );// will get some more 3152// There isn't always a NUL after the command, but it may need to be 3153// there, thus copy up to the NUL and add a NUL. 3154memmove (ccline .cmdbuff ,p , (size_t )ccline .cmdlen ); 3155ccline .cmdbuff [ccline .cmdlen ]= NUL ; 3156 3157if (ccline .xpc != NULL 3158&& ccline .xpc -> xp_pattern != NULL 3159&& ccline .xpc -> xp_context != EXPAND_NOTHING 3160&& ccline .xpc -> xp_context != EXPAND_UNSUCCESSFUL ) { 3161int i = (int )(ccline .xpc -> xp_pattern - p ); 3162 3163// If xp_pattern points inside the old cmdbuff it needs to be adjusted 3164// to point into the newly allocated memory. 3165if (i >=0 && i <=ccline .cmdlen ) { 3166ccline .xpc -> xp_pattern = ccline .cmdbuff + i ; 3167 } 3168 } 3169 3170xfree (p ); 3171} 3172 3173enum {MAX_CB_ERRORS = 1 , }; 3174 3175/// Color expression cmdline using built-in expressions parser 3176/// 3177/// @param[in] colored_ccline Command-line to color. 3178/// @param[out] ret_ccline_colors What should be colored. 3179/// 3180/// Always colors the whole cmdline. 3181static void color_expr_cmdline (const CmdlineInfo * const colored_ccline , 3182ColoredCmdline * const ret_ccline_colors ) 3183FUNC_ATTR_NONNULL_ALL 3184{ 3185ParserLine parser_lines []= { 3186 { 3187 .data = colored_ccline -> cmdbuff , 3188 .size = strlen (colored_ccline -> cmdbuff ), 3189 .allocated = false, 3190 }, 3191 {NULL ,0 , false }, 3192 }; 3193ParserLine * plines_p = parser_lines ; 3194ParserHighlight colors ; 3195kvi_init (colors ); 3196ParserState pstate ; 3197viml_parser_init (& pstate ,parser_simple_get_line ,& plines_p ,& colors ); 3198ExprAST east = viml_pexpr_parse (& pstate ,kExprFlagsDisallowEOC ); 3199viml_pexpr_free_ast (east ); 3200viml_parser_destroy (& pstate ); 3201kv_resize (ret_ccline_colors -> colors ,kv_size (colors )); 3202size_t prev_end = 0 ; 3203for (size_t i = 0 ;i < kv_size (colors );i ++ ) { 3204const ParserHighlightChunk chunk = kv_A (colors ,i ); 3205assert (chunk .start .col < INT_MAX ); 3206assert (chunk .end_col < INT_MAX ); 3207if (chunk .start .col != prev_end ) { 3208kv_push (ret_ccline_colors -> colors , ((CmdlineColorChunk ) { 3209 .start = (int )prev_end , 3210 .end = (int )chunk .start .col , 3211 .hl_id = 0 , 3212 })); 3213 } 3214kv_push (ret_ccline_colors -> colors , ((CmdlineColorChunk ) { 3215 .start = (int )chunk .start .col , 3216 .end = (int )chunk .end_col , 3217 .hl_id = syn_name2id (chunk .group ), 3218 })); 3219prev_end = chunk .end_col ; 3220 } 3221if (prev_end < (size_t )colored_ccline -> cmdlen ) { 3222kv_push (ret_ccline_colors -> colors , ((CmdlineColorChunk ) { 3223 .start = (int )prev_end , 3224 .end = colored_ccline -> cmdlen , 3225 .hl_id = 0 , 3226 })); 3227 } 3228kvi_destroy (colors ); 3229} 3230 3231/// Color command-line 3232/// 3233/// Should use built-in command parser or user-specified one. Currently only the 3234/// latter is supported. 3235/// 3236/// @param[in,out] colored_ccline Command-line to color. Also holds a cache: 3237/// if ->prompt_id and ->cmdbuff values happen 3238/// to be equal to those from colored_cmdline it 3239/// will just do nothing, assuming that ->colors 3240/// already contains needed data. 3241/// 3242/// Always colors the whole cmdline. 3243/// 3244/// @return true if draw_cmdline may proceed, false if it does not need anything 3245/// to do. 3246static bool color_cmdline (CmdlineInfo * colored_ccline ) 3247FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 3248{ 3249bool printed_errmsg = false; 3250 3251#define PRINT_ERRMSG (...) \ 3252 do { \ 3253 msg_scroll = true; \ 3254 msg_putchar('\n'); \ 3255 smsg(HLF_E, __VA_ARGS__); \ 3256 printed_errmsg = true; \ 3257 } while (0) 3258bool ret = true; 3259 3260ColoredCmdline * ccline_colors = & colored_ccline -> last_colors ; 3261 3262// Check whether result of the previous call is still valid. 3263if (ccline_colors -> prompt_id == colored_ccline -> prompt_id 3264&& ccline_colors -> cmdbuff != NULL 3265&& strcmp (ccline_colors -> cmdbuff ,colored_ccline -> cmdbuff )== 0 ) { 3266return ret ; 3267 } 3268 3269kv_size (ccline_colors -> colors )= 0 ; 3270 3271if (colored_ccline -> cmdbuff == NULL || * colored_ccline -> cmdbuff == NUL ) { 3272// Nothing to do, exiting. 3273XFREE_CLEAR (ccline_colors -> cmdbuff ); 3274return ret ; 3275 } 3276 3277bool arg_allocated = false; 3278typval_T arg = { 3279 .v_type = VAR_STRING , 3280 .vval .v_string = colored_ccline -> cmdbuff , 3281 }; 3282typval_T tv = { .v_type = VAR_UNKNOWN }; 3283 3284static unsigned prev_prompt_id = UINT_MAX ; 3285static int prev_prompt_errors = 0 ; 3286Callback color_cb = CALLBACK_NONE ; 3287bool can_free_cb = false; 3288Error err = ERROR_INIT ; 3289const char * err_errmsg = e_intern2 ; 3290bool dgc_ret = true; 3291 3292if (colored_ccline -> prompt_id != prev_prompt_id ) { 3293prev_prompt_errors = 0 ; 3294prev_prompt_id = colored_ccline -> prompt_id ; 3295 }else if (prev_prompt_errors >=MAX_CB_ERRORS ) { 3296 gotocolor_cmdline_end ; 3297 } 3298if (colored_ccline -> highlight_callback .type != kCallbackNone ) { 3299// Currently this should only happen while processing input() prompts. 3300assert (colored_ccline -> input_fn ); 3301color_cb = colored_ccline -> highlight_callback ; 3302 }else if (colored_ccline -> cmdfirstc == ':' ) { 3303TRY_WRAP (& err , { 3304err_errmsg = N_ ("E5408: Unable to get g:Nvim_color_cmdline callback: %s" ); 3305dgc_ret = tv_dict_get_callback (get_globvar_dict (),S_LEN ("Nvim_color_cmdline" ), 3306& color_cb ); 3307 }); 3308can_free_cb = true; 3309 }else if (colored_ccline -> cmdfirstc == '=' ) { 3310color_expr_cmdline (colored_ccline ,ccline_colors ); 3311 } 3312if (ERROR_SET (& err )|| !dgc_ret ) { 3313 gotocolor_cmdline_error ; 3314 } 3315 3316if (color_cb .type == kCallbackNone ) { 3317 gotocolor_cmdline_end ; 3318 } 3319if (colored_ccline -> cmdbuff [colored_ccline -> cmdlen ]!= NUL ) { 3320arg_allocated = true; 3321arg .vval .v_string = xmemdupz (colored_ccline -> cmdbuff , (size_t )colored_ccline -> cmdlen ); 3322 } 3323// msg_start() called by e.g. :echo may shift command-line to the first column 3324// even though msg_silent is here. Two ways to workaround this problem without 3325// altering message.c: use full_screen or save and restore msg_col. 3326// 3327// Saving and restoring full_screen does not work well with :redraw!. Saving 3328// and restoring msg_col is neither ideal, but while with full_screen it 3329// appears shifted one character to the right and cursor position is no longer 3330// correct, with msg_col it just misses leading `:`. Since `redraw!` in 3331// callback lags this is least of the user problems. 3332// 3333// Also using TRY_WRAP because error messages may overwrite typed 3334// command-line which is not expected. 3335getln_interrupted_highlight = false; 3336bool cbcall_ret = true; 3337TRY_WRAP (& err , { 3338err_errmsg = N_ ("E5407: Callback has thrown an exception: %s" ); 3339const int saved_msg_col = msg_col ; 3340msg_silent ++ ; 3341cbcall_ret = callback_call (& color_cb ,1 ,& arg ,& tv ); 3342msg_silent -- ; 3343msg_col = saved_msg_col ; 3344if (got_int ) { 3345getln_interrupted_highlight = true; 3346 } 3347 }); 3348if (ERROR_SET (& err )|| !cbcall_ret ) { 3349 gotocolor_cmdline_error ; 3350 } 3351if (tv .v_type != VAR_LIST ) { 3352PRINT_ERRMSG ("%s" ,_ ("E5400: Callback should return list" )); 3353 gotocolor_cmdline_error ; 3354 } 3355if (tv .vval .v_list == NULL ) { 3356 gotocolor_cmdline_end ; 3357 } 3358varnumber_T prev_end = 0 ; 3359int i = 0 ; 3360TV_LIST_ITER_CONST (tv .vval .v_list ,li , { 3361if (TV_LIST_ITEM_TV (li )-> v_type != VAR_LIST ) { 3362PRINT_ERRMSG (_ ("E5401: List item %i is not a List" ),i ); 3363 gotocolor_cmdline_error ; 3364 } 3365const list_T * const l = TV_LIST_ITEM_TV (li )-> vval .v_list ; 3366if (tv_list_len (l )!= 3 ) { 3367PRINT_ERRMSG (_ ("E5402: List item %i has incorrect length: %d /= 3" ), 3368i ,tv_list_len (l )); 3369 gotocolor_cmdline_error ; 3370 } 3371bool error = false; 3372const varnumber_T start = ( 3373tv_get_number_chk (TV_LIST_ITEM_TV (tv_list_first (l )),& error )); 3374if (error ) { 3375 gotocolor_cmdline_error ; 3376 }else if (!(prev_end <=start && start < colored_ccline -> cmdlen )) { 3377PRINT_ERRMSG (_ ("E5403: Chunk %i start %" PRIdVARNUMBER " not in range " 3378"[%" PRIdVARNUMBER ", %i)" ), 3379i ,start ,prev_end ,colored_ccline -> cmdlen ); 3380 gotocolor_cmdline_error ; 3381 }else if (utf8len_tab_zero [(uint8_t )colored_ccline -> cmdbuff [start ]]== 0 ) { 3382PRINT_ERRMSG (_ ("E5405: Chunk %i start %" PRIdVARNUMBER " splits " 3383"multibyte character" ),i ,start ); 3384 gotocolor_cmdline_error ; 3385 } 3386if (start != prev_end ) { 3387kv_push (ccline_colors -> colors , ((CmdlineColorChunk ) { 3388 .start = (int )prev_end , 3389 .end = (int )start , 3390 .hl_id = 0 , 3391 })); 3392 } 3393const varnumber_T end = 3394tv_get_number_chk (TV_LIST_ITEM_TV (TV_LIST_ITEM_NEXT (l ,tv_list_first (l ))),& error ); 3395if (error ) { 3396 gotocolor_cmdline_error ; 3397 }else if (!(start < end && end <=colored_ccline -> cmdlen )) { 3398PRINT_ERRMSG (_ ("E5404: Chunk %i end %" PRIdVARNUMBER " not in range " 3399"(%" PRIdVARNUMBER ", %i]" ), 3400i ,end ,start ,colored_ccline -> cmdlen ); 3401 gotocolor_cmdline_error ; 3402 }else if (end < colored_ccline -> cmdlen 3403&& (utf8len_tab_zero [(uint8_t )colored_ccline -> cmdbuff [end ]] 3404== 0 )) { 3405PRINT_ERRMSG (_ ("E5406: Chunk %i end %" PRIdVARNUMBER " splits multibyte " 3406"character" ),i ,end ); 3407 gotocolor_cmdline_error ; 3408 } 3409prev_end = end ; 3410const char * const group = tv_get_string_chk (TV_LIST_ITEM_TV (tv_list_last (l ))); 3411if (group == NULL ) { 3412 gotocolor_cmdline_error ; 3413 } 3414kv_push (ccline_colors -> colors , ((CmdlineColorChunk ) { 3415 .start = (int )start , 3416 .end = (int )end , 3417 .hl_id = syn_name2id (group ), 3418 })); 3419i ++ ; 3420 }); 3421if (prev_end < colored_ccline -> cmdlen ) { 3422kv_push (ccline_colors -> colors , ((CmdlineColorChunk ) { 3423 .start = (int )prev_end , 3424 .end = colored_ccline -> cmdlen , 3425 .hl_id = 0 , 3426 })); 3427 } 3428prev_prompt_errors = 0 ; 3429color_cmdline_end : 3430assert (!ERROR_SET (& err )); 3431if (can_free_cb ) { 3432callback_free (& color_cb ); 3433 } 3434xfree (ccline_colors -> cmdbuff ); 3435// Note: errors “output” is cached just as well as regular results. 3436ccline_colors -> prompt_id = colored_ccline -> prompt_id ; 3437if (arg_allocated ) { 3438ccline_colors -> cmdbuff = arg .vval .v_string ; 3439 }else { 3440ccline_colors -> cmdbuff = xmemdupz (colored_ccline -> cmdbuff , (size_t )colored_ccline -> cmdlen ); 3441 } 3442tv_clear (& tv ); 3443return ret ; 3444color_cmdline_error : 3445if (ERROR_SET (& err )) { 3446PRINT_ERRMSG (_ (err_errmsg ),err .msg ); 3447api_clear_error (& err ); 3448 } 3449assert (printed_errmsg ); 3450 (void )printed_errmsg ; 3451 3452prev_prompt_errors ++ ; 3453kv_size (ccline_colors -> colors )= 0 ; 3454redrawcmdline (); 3455ret = false; 3456 gotocolor_cmdline_end ; 3457#undef PRINT_ERRMSG 3458} 3459 3460// Draw part of the cmdline at the current cursor position. But draw stars 3461// when cmdline_star is true. 3462static void draw_cmdline (int start ,int len ) 3463{ 3464if (ccline .cmdbuff == NULL || !color_cmdline (& ccline )) { 3465return ; 3466 } 3467 3468if (ui_has (kUICmdline )) { 3469ccline .special_char = NUL ; 3470ccline .redraw_state = kCmdRedrawAll ; 3471return ; 3472 } 3473 3474if (cmdline_star > 0 ) { 3475for (int i = 0 ;i < len ;i ++ ) { 3476msg_putchar ('*' ); 3477i += utfc_ptr2len (ccline .cmdbuff + start + i )- 1 ; 3478 } 3479 }else { 3480if (kv_size (ccline .last_colors .colors )) { 3481for (size_t i = 0 ;i < kv_size (ccline .last_colors .colors );i ++ ) { 3482CmdlineColorChunk chunk = kv_A (ccline .last_colors .colors ,i ); 3483if (chunk .end <=start ) { 3484continue ; 3485 } 3486const int chunk_start = MAX (chunk .start ,start ); 3487msg_outtrans_len (ccline .cmdbuff + chunk_start ,chunk .end - chunk_start ,chunk .hl_id , false); 3488 } 3489 }else { 3490msg_outtrans_len (ccline .cmdbuff + start ,len ,0 , false); 3491 } 3492 } 3493} 3494 3495static void ui_ext_cmdline_show (CmdlineInfo * line ) 3496{ 3497Arena arena = ARENA_EMPTY ; 3498Array content ; 3499if (cmdline_star ) { 3500content = arena_array (& arena ,1 ); 3501size_t len = 0 ; 3502for (char * p = ccline .cmdbuff ;* p ;MB_PTR_ADV (p )) { 3503len ++ ; 3504 } 3505char * buf = arena_alloc (& arena ,len , false); 3506memset (buf ,'*' ,len ); 3507Array item = arena_array (& arena ,3 ); 3508ADD_C (item ,INTEGER_OBJ (0 )); 3509ADD_C (item ,STRING_OBJ (cbuf_as_string (buf ,len ))); 3510ADD_C (item ,INTEGER_OBJ (0 )); 3511ADD_C (content ,ARRAY_OBJ (item )); 3512 }else if (kv_size (line -> last_colors .colors )) { 3513content = arena_array (& arena ,kv_size (line -> last_colors .colors )); 3514for (size_t i = 0 ;i < kv_size (line -> last_colors .colors );i ++ ) { 3515CmdlineColorChunk chunk = kv_A (line -> last_colors .colors ,i ); 3516Array item = arena_array (& arena ,3 ); 3517ADD_C (item ,INTEGER_OBJ (chunk .hl_id == 0 ?0 :syn_id2attr (chunk .hl_id ))); 3518 3519assert (chunk .end >=chunk .start ); 3520ADD_C (item ,STRING_OBJ (cbuf_as_string (line -> cmdbuff + chunk .start , 3521 (size_t )(chunk .end - chunk .start )))); 3522ADD_C (item ,INTEGER_OBJ (chunk .hl_id )); 3523ADD_C (content ,ARRAY_OBJ (item )); 3524 } 3525 }else { 3526Array item = arena_array (& arena ,3 ); 3527ADD_C (item ,INTEGER_OBJ (0 )); 3528ADD_C (item ,CSTR_AS_OBJ (line -> cmdbuff )); 3529ADD_C (item ,INTEGER_OBJ (0 )); 3530content = arena_array (& arena ,1 ); 3531ADD_C (content ,ARRAY_OBJ (item )); 3532 } 3533char charbuf [2 ]= { (char )line -> cmdfirstc ,0 }; 3534ui_call_cmdline_show (content ,line -> cmdpos , 3535cstr_as_string (charbuf ), 3536cstr_as_string (line -> cmdprompt ), 3537line -> cmdindent ,line -> level ,line -> cmdprompt ?line -> hl_id :-1 ); 3538if (line -> special_char ) { 3539charbuf [0 ]= line -> special_char ; 3540ui_call_cmdline_special_char (cstr_as_string (charbuf ), 3541line -> special_shift , 3542line -> level ); 3543 } 3544arena_mem_free (arena_finish (& arena )); 3545} 3546 3547void ui_ext_cmdline_block_append (size_t indent ,const char * line ) 3548{ 3549char * buf = xmallocz (indent + strlen (line )); 3550memset (buf ,' ' ,indent ); 3551memcpy (buf + indent ,line ,strlen (line )); 3552 3553Array item = ARRAY_DICT_INIT ; 3554ADD (item ,INTEGER_OBJ (0 )); 3555ADD (item ,CSTR_AS_OBJ (buf )); 3556ADD (item ,INTEGER_OBJ (0 )); 3557Array content = ARRAY_DICT_INIT ; 3558ADD (content ,ARRAY_OBJ (item )); 3559ADD (cmdline_block ,ARRAY_OBJ (content )); 3560if (cmdline_block .size > 1 ) { 3561ui_call_cmdline_block_append (content ); 3562 }else { 3563ui_call_cmdline_block_show (cmdline_block ); 3564 } 3565} 3566 3567void ui_ext_cmdline_block_leave (void ) 3568{ 3569api_free_array (cmdline_block ); 3570cmdline_block = (Array )ARRAY_DICT_INIT ; 3571ui_call_cmdline_block_hide (); 3572} 3573 3574/// Extra redrawing needed for redraw! and on ui_attach. 3575void cmdline_screen_cleared (void ) 3576{ 3577if (!ui_has (kUICmdline )) { 3578return ; 3579 } 3580 3581if (cmdline_block .size ) { 3582ui_call_cmdline_block_show (cmdline_block ); 3583 } 3584 3585int prev_level = ccline .level - 1 ; 3586CmdlineInfo * line = ccline .prev_ccline ; 3587while (prev_level > 0 && line ) { 3588if (line -> level == prev_level ) { 3589// Always redraw (cmdwin is not special since #40312). 3590line -> redraw_state = kCmdRedrawAll ; 3591prev_level -- ; 3592 } 3593line = line -> prev_ccline ; 3594 } 3595redrawcmd (); 3596} 3597 3598/// called by ui_flush, do what redraws necessary to keep cmdline updated. 3599void cmdline_ui_flush (void ) 3600{ 3601if (!ui_has (kUICmdline )) { 3602return ; 3603 } 3604int level = ccline .level ; 3605CmdlineInfo * line = & ccline ; 3606while (level > 0 && line ) { 3607if (line -> level == level ) { 3608CmdRedraw redraw_state = line -> redraw_state ; 3609line -> redraw_state = kCmdRedrawNone ; 3610if (redraw_state == kCmdRedrawAll ) { 3611cmdline_was_last_drawn = true; 3612ui_ext_cmdline_show (line ); 3613 }else if (redraw_state == kCmdRedrawPos && cmdline_was_last_drawn ) { 3614ui_call_cmdline_pos (line -> cmdpos ,line -> level ); 3615 } 3616level -- ; 3617 } 3618line = line -> prev_ccline ; 3619 } 3620} 3621 3622// Put a character on the command line. Shifts the following text to the 3623// right when "shift" is true. Used for CTRL-V, CTRL-K, etc. 3624// "c" must be printable (fit in one display cell)! 3625void putcmdline (char c ,bool shift ) 3626{ 3627if (cmd_silent ) { 3628return ; 3629 } 3630if (!ui_has (kUICmdline )) { 3631msg_no_more = true; 3632msg_putchar (c ); 3633if (shift ) { 3634draw_cmdline (ccline .cmdpos ,ccline .cmdlen - ccline .cmdpos ); 3635 } 3636msg_no_more = false; 3637 }else if (ccline .redraw_state != kCmdRedrawAll ) { 3638char charbuf [2 ]= {c ,0 }; 3639ui_call_cmdline_special_char (cstr_as_string (charbuf ),shift , 3640ccline .level ); 3641 } 3642cursorcmd (); 3643ccline .special_char = c ; 3644ccline .special_shift = shift ; 3645ui_cursor_shape (); 3646} 3647 3648/// Undo a putcmdline(c, false). 3649void unputcmdline (void ) 3650{ 3651if (cmd_silent ) { 3652return ; 3653 } 3654msg_no_more = true; 3655if (ccline .cmdlen == ccline .cmdpos && !ui_has (kUICmdline )) { 3656msg_putchar (' ' ); 3657 }else { 3658draw_cmdline (ccline .cmdpos ,utfc_ptr2len (ccline .cmdbuff + ccline .cmdpos )); 3659 } 3660msg_no_more = false; 3661cursorcmd (); 3662ccline .special_char = NUL ; 3663ui_cursor_shape (); 3664} 3665 3666// Put the given string, of the given length, onto the command line. 3667// If len is -1, then strlen() is used to calculate the length. 3668// If 'redraw' is true then the new part of the command line, and the remaining 3669// part will be redrawn, otherwise it will not. If this function is called 3670// twice in a row, then 'redraw' should be false and redrawcmd() should be 3671// called afterwards. 3672void put_on_cmdline (const char * str ,int len ,bool redraw ) 3673{ 3674if (len < 0 ) { 3675len = (int )strlen (str ); 3676 } 3677 3678realloc_cmdbuff (ccline .cmdlen + len + 1 ); 3679 3680if (!ccline .overstrike ) { 3681memmove (ccline .cmdbuff + ccline .cmdpos + len , 3682ccline .cmdbuff + ccline .cmdpos , 3683 (size_t )(ccline .cmdlen - ccline .cmdpos )); 3684ccline .cmdlen += len ; 3685 }else { 3686// Count nr of characters in the new string. 3687int m = 0 ; 3688int i ; 3689for (i = 0 ;i < len ;i += utfc_ptr2len (str + i )) { 3690m ++ ; 3691 } 3692// Count nr of bytes in cmdline that are overwritten by these 3693// characters. 3694for (i = ccline .cmdpos ;i < ccline .cmdlen && m > 0 ; 3695i += utfc_ptr2len (ccline .cmdbuff + i )) { 3696m -- ; 3697 } 3698if (i < ccline .cmdlen ) { 3699memmove (ccline .cmdbuff + ccline .cmdpos + len , 3700ccline .cmdbuff + i , (size_t )(ccline .cmdlen - i )); 3701ccline .cmdlen += ccline .cmdpos + len - i ; 3702 }else { 3703ccline .cmdlen = ccline .cmdpos + len ; 3704 } 3705 } 3706memmove (ccline .cmdbuff + ccline .cmdpos ,str , (size_t )len ); 3707ccline .cmdbuff [ccline .cmdlen ]= NUL ; 3708 3709// When the inserted text starts with a composing character, 3710// backup to the character before it. 3711if (ccline .cmdpos > 0 && (uint8_t )ccline .cmdbuff [ccline .cmdpos ] >=0x80 ) { 3712int i = utf_head_off (ccline .cmdbuff ,ccline .cmdbuff + ccline .cmdpos ); 3713if (i != 0 ) { 3714ccline .cmdpos -= i ; 3715len += i ; 3716ccline .cmdspos = cmd_screencol (ccline .cmdpos ); 3717 } 3718 } 3719 3720if (redraw && !cmd_silent ) { 3721msg_no_more = true; 3722int i = cmdline_row ; 3723cursorcmd (); 3724draw_cmdline (ccline .cmdpos ,ccline .cmdlen - ccline .cmdpos ); 3725// Avoid clearing the rest of the line too often. 3726if (cmdline_row != i || ccline .overstrike ) { 3727msg_clr_eos (); 3728 } 3729msg_no_more = false; 3730 } 3731int m ; 3732if (KeyTyped ) { 3733m = Columns * Rows ; 3734if (m < 0 ) {// overflow, Columns or Rows at weird value 3735m = MAXCOL ; 3736 } 3737 }else { 3738m = MAXCOL ; 3739 } 3740for (int i = 0 ;i < len ;i ++ ) { 3741int c = cmdline_charsize (ccline .cmdpos ); 3742// count ">" for a double-wide char that doesn't fit. 3743correct_screencol (ccline .cmdpos ,c ,& ccline .cmdspos ); 3744// Stop cursor at the end of the screen, but do increment the 3745// insert position, so that entering a very long command 3746// works, even though you can't see it. 3747if (ccline .cmdspos + c < m ) { 3748ccline .cmdspos += c ; 3749 } 3750c = utfc_ptr2len (ccline .cmdbuff + ccline .cmdpos )- 1 ; 3751c = MIN (c ,len - i - 1 ); 3752ccline .cmdpos += c ; 3753i += c ; 3754ccline .cmdpos ++ ; 3755 } 3756 3757if (redraw ) { 3758msg_check (); 3759 } 3760} 3761 3762/// Save ccline, because obtaining the "=" register may execute "normal :cmd" 3763/// and overwrite it. 3764static void save_cmdline (CmdlineInfo * ccp ) 3765{ 3766* ccp = ccline ; 3767CLEAR_FIELD (ccline ); 3768ccline .prev_ccline = ccp ; 3769ccline .cmdbuff = NULL ;// signal that ccline is not in use 3770} 3771 3772/// Restore ccline after it has been saved with save_cmdline(). 3773static void restore_cmdline (CmdlineInfo * ccp ) 3774FUNC_ATTR_NONNULL_ALL 3775{ 3776ccline = * ccp ; 3777} 3778 3779/// Paste a yank register into the command line. 3780/// Used by CTRL-R command in command-line mode. 3781/// insert_reg() can't be used here, because special characters from the 3782/// register contents will be interpreted as commands. 3783/// 3784/// @param regname Register name. 3785/// @param literally Insert text literally instead of "as typed". 3786/// @param remcr When true, remove trailing CR. 3787/// 3788/// @returns FAIL for failure, OK otherwise 3789static bool cmdline_paste (int regname ,bool literally ,bool remcr ) 3790{ 3791char * arg ; 3792bool allocated ; 3793 3794// check for valid regname; also accept special characters for CTRL-R in 3795// the command line 3796if (regname != Ctrl_F && regname != Ctrl_P && regname != Ctrl_W 3797&& regname != Ctrl_A && regname != Ctrl_L 3798&& !valid_yank_reg (regname , false)) { 3799return FAIL ; 3800 } 3801 3802// A register containing CTRL-R can cause an endless loop. Allow using 3803// CTRL-C to break the loop. 3804line_breakcheck (); 3805if (got_int ) { 3806return FAIL ; 3807 } 3808 3809// Need to set "textlock" to avoid nasty things like going to another 3810// buffer when evaluating an expression. 3811textlock ++ ; 3812const bool i = get_spec_reg (regname ,& arg ,& allocated , true); 3813textlock -- ; 3814 3815if (i ) { 3816// Got the value of a special register in "arg". 3817if (arg == NULL ) { 3818return FAIL ; 3819 } 3820 3821// When 'incsearch' is set and CTRL-R CTRL-W used: skip the duplicate 3822// part of the word. 3823char * p = arg ; 3824if (p_is && regname == Ctrl_W ) { 3825char * w ; 3826int len ; 3827 3828// Locate start of last word in the cmd buffer. 3829for (w = ccline .cmdbuff + ccline .cmdpos ;w > ccline .cmdbuff ;) { 3830len = utf_head_off (ccline .cmdbuff ,w - 1 )+ 1 ; 3831if (!vim_iswordc (utf_ptr2char (w - len ))) { 3832break ; 3833 } 3834w -= len ; 3835 } 3836len = (int )((ccline .cmdbuff + ccline .cmdpos )- w ); 3837if (p_ic ?STRNICMP (w ,arg , (size_t )len )== 0 :strncmp (w ,arg , (size_t )len )== 0 ) { 3838p += len ; 3839 } 3840 } 3841 3842cmdline_paste_str (p ,literally ); 3843if (allocated ) { 3844xfree (arg ); 3845 } 3846return OK ; 3847 } 3848 3849return cmdline_paste_reg (regname ,literally ,remcr ); 3850} 3851 3852// Put a string on the command line. 3853// When "literally" is true, insert literally. 3854// When "literally" is false, insert as typed, but don't leave the command 3855// line. 3856void cmdline_paste_str (const char * s ,bool literally ) 3857{ 3858if (literally ) { 3859put_on_cmdline (s ,-1 , true); 3860 }else { 3861while (* s != NUL ) { 3862int cv = (uint8_t )(* s ); 3863if (cv == Ctrl_V && s [1 ]) { 3864s ++ ; 3865 } 3866int c = mb_cptr2char_adv (& s ); 3867if (cv == Ctrl_V || c == ESC || c == Ctrl_C 3868|| c == CAR || c == NL || c == Ctrl_L 3869|| (c == Ctrl_BSL && * s == Ctrl_N )) { 3870stuffcharReadbuff (Ctrl_V ); 3871 } 3872stuffcharReadbuff (c ); 3873 } 3874 } 3875} 3876 3877// This function is called when the screen size changes and with incremental 3878// search and in other situations where the command line may have been 3879// overwritten. 3880void redrawcmdline (void ) 3881{ 3882if (cmd_silent ) { 3883return ; 3884 } 3885need_wait_return = false; 3886compute_cmdrow (); 3887redrawcmd (); 3888cursorcmd (); 3889ui_cursor_shape (); 3890} 3891 3892static void redrawcmdprompt (void ) 3893{ 3894if (cmd_silent ) { 3895return ; 3896 } 3897if (ui_has (kUICmdline )) { 3898ccline .redraw_state = kCmdRedrawAll ; 3899return ; 3900 } 3901if (ccline .cmdfirstc != NUL ) { 3902msg_putchar (ccline .cmdfirstc ); 3903 } 3904if (ccline .cmdprompt != NULL ) { 3905msg_puts_hl (ccline .cmdprompt ,ccline .hl_id , false); 3906ccline .cmdindent = msg_col + (msg_row - cmdline_row )* Columns ; 3907// do the reverse of cmd_startcol() 3908if (ccline .cmdfirstc != NUL ) { 3909ccline .cmdindent -- ; 3910 } 3911 }else { 3912for (int i = ccline .cmdindent ;i > 0 ;i -- ) { 3913msg_putchar (' ' ); 3914 } 3915 } 3916} 3917 3918// Redraw what is currently on the command line. 3919void redrawcmd (void ) 3920{ 3921if (cmd_silent ) { 3922return ; 3923 } 3924 3925if (ui_has (kUICmdline )) { 3926draw_cmdline (0 ,ccline .cmdlen ); 3927return ; 3928 } 3929 3930// when 'incsearch' is set there may be no command line while redrawing 3931if (ccline .cmdbuff == NULL ) { 3932msg_cursor_goto (cmdline_row ,0 ); 3933msg_clr_eos (); 3934return ; 3935 } 3936 3937redrawing_cmdline = true; 3938 3939sb_text_restart_cmdline (); 3940msg_start (); 3941// Reset lines_left so a wrapped cmdline isn't truncated by msg_no_more. 3942msg_starthere (); 3943redrawcmdprompt (); 3944 3945// Don't use more prompt, truncate the cmdline if it doesn't fit. 3946msg_no_more = true; 3947draw_cmdline (0 ,ccline .cmdlen ); 3948msg_clr_eos (); 3949msg_no_more = false; 3950 3951ccline .cmdspos = cmd_screencol (ccline .cmdpos ); 3952 3953if (ccline .special_char != NUL ) { 3954putcmdline (ccline .special_char ,ccline .special_shift ); 3955 } 3956 3957// An emsg() before may have set msg_scroll. This is used in normal mode, 3958// in cmdline mode we can reset them now. 3959msg_scroll = false;// next message overwrites cmdline 3960 3961// Typing ':' at the more prompt may set skip_redraw. We don't want this 3962// in cmdline mode. 3963skip_redraw = false; 3964cmdline_was_last_drawn = true; 3965redrawing_cmdline = false; 3966} 3967 3968void compute_cmdrow (void ) 3969{ 3970if (msg_scrolled != 0 ) { 3971cmdline_row = Rows - 1 ; 3972 }else { 3973win_T * wp = lastwin_nofloating (NULL ); 3974cmdline_row = wp -> w_winrow + wp -> w_height 3975+ wp -> w_hsep_height + wp -> w_status_height + global_stl_height (); 3976 } 3977if (cmdline_row == Rows && p_ch > 0 ) { 3978cmdline_row -- ; 3979 } 3980lines_left = cmdline_row ; 3981} 3982 3983void cursorcmd (void ) 3984{ 3985if (cmd_silent || ui_has (kUICmdline )) { 3986return ; 3987 } 3988 3989msg_row = cmdline_row + (ccline .cmdspos /Columns ); 3990msg_col = ccline .cmdspos %Columns ; 3991msg_row = MIN (msg_row ,Rows - 1 ); 3992 3993msg_cursor_goto (msg_row ,msg_col ); 3994} 3995 3996void gotocmdline (bool clr ) 3997{ 3998if (ui_has (kUICmdline )) { 3999return ; 4000 } 4001msg_start (); 4002msg_col = 0 ;// always start in column 0 4003if (clr ) {// clear the bottom line(s) 4004msg_clr_eos ();// will reset clear_cmdline 4005 } 4006msg_cursor_goto (cmdline_row ,0 ); 4007} 4008 4009// Check the word in front of the cursor for an abbreviation. 4010// Called when the non-id character "c" has been entered. 4011// When an abbreviation is recognized it is removed from the text with 4012// backspaces and the replacement string is inserted, followed by "c". 4013static int ccheck_abbr (int c ) 4014{ 4015int spos = 0 ; 4016 4017if (p_paste || no_abbr ) {// no abbreviations or in paste mode 4018return false; 4019 } 4020 4021// Do not consider '<,'> be part of the mapping, skip leading whitespace. 4022// Actually accepts any mark. 4023while (spos < ccline .cmdlen && ascii_iswhite (ccline .cmdbuff [spos ])) { 4024spos ++ ; 4025 } 4026if (ccline .cmdlen - spos > 5 4027&& ccline .cmdbuff [spos ]== '\'' 4028&& ccline .cmdbuff [spos + 2 ]== ',' 4029&& ccline .cmdbuff [spos + 3 ]== '\'' ) { 4030spos += 5 ; 4031 }else { 4032// check abbreviation from the beginning of the commandline 4033spos = 0 ; 4034 } 4035 4036return check_abbr (c ,ccline .cmdbuff ,ccline .cmdpos ,spos ); 4037} 4038 4039/// Escape special characters in "fname", depending on "what": 4040/// 4041/// @param[in] fname File name to escape. 4042/// @param[in] what What to escape for: 4043/// - VSE_NONE: for when used as a file name argument after a Vim command. 4044/// - VSE_SHELL: for a shell command. 4045/// - VSE_BUFFER: for the ":buffer" command. 4046/// 4047/// @return [allocated] escaped file name. 4048char * vim_strsave_fnameescape (const char * const fname ,const int what ) 4049FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL 4050{ 4051#ifdef BACKSLASH_IN_FILENAME 4052# define PATH_ESC_CHARS " \t\n*?[{`%#'\"|!<" 4053// '%' and '#' are not escaped for ":buffer": it has no EX_XFILE, so they are 4054// not expanded, and escaping them as "\%"/"\#" breaks buffer name matching 4055// when '%'/'#' is in 'isfname' (backslash treated as a path separator). 4056# define BUFFER_ESC_CHARS (" \t\n*?[`'\"|!<") 4057char buf [sizeof (PATH_ESC_CHARS )]; 4058int j = 0 ; 4059 4060// Don't escape '[', '{' and '!' if they are in 'isfname' and for the 4061// ":buffer" command. 4062for (const char * p = what == VSE_BUFFER ?BUFFER_ESC_CHARS :PATH_ESC_CHARS ; 4063* p != NUL ;p ++ ) { 4064if ((* p != '[' && * p != '{' && * p != '!' )|| !vim_isfilec ((uint8_t )(* p ))) { 4065buf [j ++ ]= * p ; 4066 } 4067 } 4068buf [j ]= NUL ; 4069char * p = vim_strsave_escaped (fname ,buf ); 4070#else 4071# define PATH_ESC_CHARS " \t\n*?[{`$\\%#'\"|!<" 4072# define SHELL_ESC_CHARS " \t\n*?[{`$\\%#'\"|!<>();&" 4073# define BUFFER_ESC_CHARS " \t\n*?[`$\\%#'\"|!<" 4074char * p = vim_strsave_escaped (fname , 4075what == VSE_SHELL ?SHELL_ESC_CHARS :what == 4076VSE_BUFFER ?BUFFER_ESC_CHARS :PATH_ESC_CHARS ); 4077if (what == VSE_SHELL && csh_like_shell ()) { 4078// For csh and similar shells need to put two backslashes before '!'. 4079// One is taken by Vim, one by the shell. 4080char * s = vim_strsave_escaped (p ,"!" ); 4081xfree (p ); 4082p = s ; 4083 } 4084#endif 4085 4086// '>' and '+' are special at the start of some commands, e.g. ":edit" and 4087// ":write". "cd -" has a special meaning. 4088if (* p == '>' || * p == '+' || (* p == '-' && p [1 ]== NUL )) { 4089escape_fname (& p ); 4090 } 4091 4092return p ; 4093} 4094 4095/// Put a backslash before the file name in "pp", which is in allocated memory. 4096void escape_fname (char ** pp ) 4097{ 4098char * p = xmalloc (strlen (* pp )+ 2 ); 4099p [0 ]= '\\' ; 4100STRCPY (p + 1 ,* pp ); 4101xfree (* pp ); 4102* pp = p ; 4103} 4104 4105/// For each file name in files[num_files]: 4106/// If 'orig_pat' starts with "~/", replace the home directory with "~". 4107void tilde_replace (char * orig_pat ,int num_files ,char ** files ) 4108{ 4109if (orig_pat [0 ]== '~' && vim_ispathsep (orig_pat [1 ])) { 4110for (int i = 0 ;i < num_files ;i ++ ) { 4111char * p = home_replace_save (NULL ,files [i ]); 4112xfree (files [i ]); 4113files [i ]= p ; 4114 } 4115 } 4116} 4117 4118/// Get a pointer to the current command line info. 4119CmdlineInfo * get_cmdline_info (void ) 4120{ 4121return & ccline ; 4122} 4123 4124unsigned get_cmdline_last_prompt_id (void ) 4125{ 4126return last_prompt_id ; 4127} 4128 4129/// Get pointer to the command line info to use. save_cmdline() may clear 4130/// ccline and put the previous value in ccline.prev_ccline. 4131static CmdlineInfo * get_ccline_ptr (void ) 4132{ 4133if ((State & MODE_CMDLINE )== 0 ) { 4134return NULL ; 4135 }else if (ccline .cmdbuff != NULL ) { 4136return & ccline ; 4137 }else if (ccline .prev_ccline && ccline .prev_ccline -> cmdbuff != NULL ) { 4138return ccline .prev_ccline ; 4139 }else { 4140return NULL ; 4141 } 4142} 4143 4144/// Get the current command-line type. 4145/// Returns ':' or '/' or '?' or '@' or '>' or '-' 4146/// Only works when the command line is being edited. 4147/// Returns NUL when something is wrong. 4148static int get_cmdline_type (void ) 4149{ 4150CmdlineInfo * p = get_ccline_ptr (); 4151 4152if (p == NULL ) { 4153return NUL ; 4154 } 4155if (p -> cmdfirstc == NUL ) { 4156return (p -> input_fn ) ?'@' :'-' ; 4157 } 4158return p -> cmdfirstc ; 4159} 4160 4161/// Get the current command line in allocated memory. 4162/// Only works when the command line is being edited. 4163/// 4164/// @return NULL when something is wrong. 4165static char * get_cmdline_str (void ) 4166{ 4167if (cmdline_star > 0 ) { 4168return NULL ; 4169 } 4170CmdlineInfo * p = get_ccline_ptr (); 4171 4172if (p == NULL ) { 4173return NULL ; 4174 } 4175return xstrnsave (p -> cmdbuff , (size_t )p -> cmdlen ); 4176} 4177 4178/// Get the current command-line completion pattern. 4179static char * get_cmdline_completion_pattern (void ) 4180{ 4181if (cmdline_star > 0 ) { 4182return NULL ; 4183 } 4184 4185CmdlineInfo * p = get_ccline_ptr (); 4186if (p == NULL || p -> xpc == NULL ) { 4187return NULL ; 4188 } 4189 4190int xp_context = p -> xpc -> xp_context ; 4191if (xp_context == EXPAND_NOTHING ) { 4192set_expand_context (p -> xpc ); 4193xp_context = p -> xpc -> xp_context ; 4194p -> xpc -> xp_context = EXPAND_NOTHING ; 4195 } 4196if (xp_context == EXPAND_UNSUCCESSFUL ) { 4197return NULL ; 4198 } 4199 4200char * compl_pat = p -> xpc -> xp_pattern ; 4201if (compl_pat == NULL ) { 4202return NULL ; 4203 } 4204 4205return xstrdup (compl_pat ); 4206} 4207 4208/// Get the command-line completion type. 4209static char * get_cmdline_completion (void ) 4210{ 4211if (cmdline_star > 0 ) { 4212return NULL ; 4213 } 4214 4215CmdlineInfo * p = get_ccline_ptr (); 4216if (p == NULL || p -> xpc == NULL ) { 4217return NULL ; 4218 } 4219 4220int xp_context = p -> xpc -> xp_context ; 4221if (xp_context == EXPAND_NOTHING ) { 4222set_expand_context (p -> xpc ); 4223xp_context = p -> xpc -> xp_context ; 4224p -> xpc -> xp_context = EXPAND_NOTHING ; 4225 } 4226if (xp_context == EXPAND_UNSUCCESSFUL ) { 4227return NULL ; 4228 } 4229 4230return cmdcomplete_type_to_str (xp_context ,p -> xpc -> xp_arg ); 4231} 4232 4233/// "getcmdcomplpat()" function 4234void f_getcmdcomplpat (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 4235{ 4236rettv -> v_type = VAR_STRING ; 4237rettv -> vval .v_string = get_cmdline_completion_pattern (); 4238} 4239 4240/// "getcmdcompltype()" function 4241void f_getcmdcompltype (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 4242{ 4243rettv -> v_type = VAR_STRING ; 4244rettv -> vval .v_string = get_cmdline_completion (); 4245} 4246 4247/// "getcmdline()" function 4248void f_getcmdline (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 4249{ 4250rettv -> v_type = VAR_STRING ; 4251rettv -> vval .v_string = get_cmdline_str (); 4252} 4253 4254/// "getcmdpos()" function 4255void f_getcmdpos (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 4256{ 4257CmdlineInfo * p = get_ccline_ptr (); 4258rettv -> vval .v_number = p != NULL ?p -> cmdpos + 1 :0 ; 4259} 4260 4261/// "getcmdprompt()" function 4262void f_getcmdprompt (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 4263{ 4264CmdlineInfo * p = get_ccline_ptr (); 4265rettv -> v_type = VAR_STRING ; 4266rettv -> vval .v_string = p != NULL && p -> cmdprompt != NULL 4267 ?xstrdup (p -> cmdprompt ) :NULL ; 4268} 4269 4270/// "getcmdscreenpos()" function 4271void f_getcmdscreenpos (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 4272{ 4273CmdlineInfo * p = get_ccline_ptr (); 4274rettv -> vval .v_number = p != NULL ?p -> cmdspos + 1 :0 ; 4275} 4276 4277/// "getcmdtype()" function 4278void f_getcmdtype (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 4279{ 4280rettv -> v_type = VAR_STRING ; 4281rettv -> vval .v_string = xmallocz (1 ); 4282rettv -> vval .v_string [0 ]= (char )get_cmdline_type (); 4283} 4284 4285/// Set the command line str to "str". 4286/// @return 1 when failed, 0 when OK. 4287static int set_cmdline_str (const char * str ,int pos ) 4288{ 4289CmdlineInfo * p = get_ccline_ptr (); 4290 4291if (p == NULL ) { 4292return 1 ; 4293 } 4294 4295int len = (int )strlen (str ); 4296realloc_cmdbuff (len + 1 ); 4297p -> cmdlen = len ; 4298STRCPY (p -> cmdbuff ,str ); 4299 4300p -> cmdpos = pos < 0 || pos > p -> cmdlen ?p -> cmdlen :pos ; 4301new_cmdpos = p -> cmdpos ; 4302p -> cmdbuff_replaced = true; 4303 4304redrawcmd (); 4305 4306// Trigger CmdlineChanged autocommands. 4307do_autocmd_cmdlinechanged (get_cmdline_type ()); 4308 4309return 0 ; 4310} 4311 4312/// Set the command line byte position to "pos". Zero is the first position. 4313/// Only works when the command line is being edited. 4314/// @return 1 when failed, 0 when OK. 4315static int set_cmdline_pos (int pos ) 4316{ 4317CmdlineInfo * p = get_ccline_ptr (); 4318 4319if (p == NULL ) { 4320return 1 ; 4321 } 4322 4323// The position is not set directly but after CTRL-\ e or CTRL-R = has 4324// changed the command line. 4325new_cmdpos = MAX (0 ,pos ); 4326 4327return 0 ; 4328} 4329 4330/// "setcmdline()" function 4331void f_setcmdline (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 4332{ 4333if (tv_check_for_string_arg (argvars ,0 )== FAIL 4334|| tv_check_for_opt_number_arg (argvars ,1 )== FAIL ) { 4335return ; 4336 } 4337 4338int pos = -1 ; 4339if (argvars [1 ].v_type != VAR_UNKNOWN ) { 4340bool error = false; 4341 4342pos = (int )tv_get_number_chk (& argvars [1 ],& error )- 1 ; 4343if (error ) { 4344return ; 4345 } 4346if (pos < 0 ) { 4347emsg (_ (e_positive )); 4348return ; 4349 } 4350 } 4351 4352// Use tv_get_string() to handle a NULL string like an empty string. 4353rettv -> vval .v_number = set_cmdline_str (tv_get_string (& argvars [0 ]),pos ); 4354} 4355 4356/// "setcmdpos()" function 4357void f_setcmdpos (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 4358{ 4359const int pos = (int )tv_get_number (& argvars [0 ])- 1 ; 4360 4361if (pos >=0 ) { 4362rettv -> vval .v_number = set_cmdline_pos (pos ); 4363 } 4364} 4365 4366/// Return the first character of the current command line. 4367int get_cmdline_firstc (void ) 4368{ 4369return ccline .cmdfirstc ; 4370} 4371 4372/// Get indices that specify a range within a list (not a range of text lines 4373/// in a buffer!) from a string. Used for ":history" and ":clist". 4374/// 4375/// @param str string to parse range from 4376/// @param num1 from 4377/// @param num2 to 4378/// 4379/// @return OK if parsed successfully, otherwise FAIL. 4380int get_list_range (char ** str ,int * num1 ,int * num2 ) 4381{ 4382int len ; 4383bool first = false; 4384varnumber_T num ; 4385 4386* str = skipwhite ((* str )); 4387if (** str == '-' || ascii_isdigit (** str )) {// parse "from" part of range 4388vim_str2nr (* str ,NULL ,& len ,0 ,& num ,NULL ,0 , false,NULL ); 4389* str += len ; 4390// overflow 4391if (num > INT_MAX ) { 4392return FAIL ; 4393 } 4394 4395* num1 = (int )num ; 4396first = true; 4397 } 4398* str = skipwhite ((* str )); 4399if (** str == ',' ) {// parse "to" part of range 4400* str = skipwhite ((* str )+ 1 ); 4401vim_str2nr (* str ,NULL ,& len ,0 ,& num ,NULL ,0 , false,NULL ); 4402if (len > 0 ) { 4403* str = skipwhite ((* str )+ len ); 4404// overflow 4405if (num > INT_MAX ) { 4406return FAIL ; 4407 } 4408 4409* num2 = (int )num ; 4410 }else if (!first ) {// no number given at all 4411return FAIL ; 4412 } 4413 }else if (first ) {// only one number given 4414* num2 = * num1 ; 4415 } 4416return OK ; 4417} 4418 4419void cmdline_init (void ) 4420{ 4421CLEAR_FIELD (ccline ); 4422} 4423 4424/// Check value of 'cedit' and set cedit_key. 4425/// Returns NULL if value is OK, error message otherwise. 4426const char * did_set_cedit (optset_T * args ) 4427{ 4428if (* p_cedit == NUL ) { 4429cedit_key = -1 ; 4430 }else { 4431int n = string_to_key (p_cedit ); 4432if (n == 0 || vim_isprintc (n )) { 4433return e_invarg ; 4434 } 4435cedit_key = n ; 4436 } 4437return NULL ; 4438} 4439 4440typedef struct { 4441int firstc ;///< ':'/'/'/'?'. 4442char * content ;///< Initial cmdline (owned). 4443int pos ;///< Cursor column. 4444}CmdwinOpenArgs ; 4445 4446/// Synchronously calls `vim._core.cmdwin.<action>(...)`. 4447static void cmdwin_invoke (const char * action ,int firstc ,char * content ,int pos ) 4448{ 4449char fc [2 ]= { (char )firstc ,0 }; 4450typval_T tv_args []= { 4451 { .v_type = VAR_STRING , .vval .v_string = fc }, 4452 { .v_type = VAR_STRING , .vval .v_string = content ?content :"" }, 4453 { .v_type = VAR_NUMBER , .vval .v_number = pos + 1 }, 4454 { .v_type = VAR_UNKNOWN }, 4455 }; 4456nlua_call_typval ("vim._core.cmdwin" ,action ,firstc ?tv_args :tv_args + 3 ,NULL ); 4457xfree (content ); 4458} 4459 4460/// Calls `vim._core.cmdwin.<action>()`, synchronously. 4461void cmdwin_do_action (const char * action ) 4462{ 4463cmdwin_invoke (action ,0 ,NULL ,0 ); 4464} 4465 4466/// Deferred event: opens cmdwin after the cmdline-reader unwinds. Can't run synchronously (cmdline 4467/// is still being read), nor via vim.schedule (could fire _during typeahead_; revisit after #40380). 4468static void open_cmdwin_event (void ** argv ) 4469{ 4470CmdwinOpenArgs * a = argv [0 ]; 4471cmdwin_invoke ("open" ,a -> firstc ,a -> content ,a -> pos );// frees a->content 4472xfree (a ); 4473} 4474 4475/// Schedules cmdwin to open after the current cmdline-reader returns. Returns Ctrl_C so the cmdline 4476/// input loop unwinds, then `vim._core.cmdwin` does its work after typeahead. #40312 4477static int open_cmdwin (void ) 4478{ 4479// Disallow during textlock or when typing a password. 4480if (text_locked ()|| cmdline_star > 0 ) { 4481beep_flush (); 4482return K_IGNORE ; 4483 } 4484// Already open (also guarded in `vim._core.cmdwin`, but check here to avoid scheduling). 4485if (cmdwin_buf != NULL ) { 4486beep_flush (); 4487return K_IGNORE ; 4488 } 4489// Disallow for expr-register and input()/inputlist(): no reentrant return path. #40407 4490int ft = get_cmdline_type (); 4491if (ft != ':' && ft != '/' && ft != '?' ) { 4492beep_flush (); 4493return K_IGNORE ; 4494 } 4495 4496CmdwinOpenArgs * a = xmalloc (sizeof (* a )); 4497a -> firstc = ft ; 4498a -> pos = ccline .cmdpos ; 4499 4500// Capture the cmdline; will append to end of cmdwin. 4501a -> content = ccline .cmdbuff ?xstrnsave (ccline .cmdbuff , (size_t )ccline .cmdlen ) :NULL ; 4502// Clear cmdline so that unwinding it (via Ctrl_C below) does not add it to history. 4503ccline .cmdlen = 0 ; 4504ccline .cmdpos = 0 ; 4505 4506// Intentionally not using vim.scheduled, see note on `open_cmdwin_event`. 4507loop_schedule_deferred (& main_loop ,event_create (open_cmdwin_event ,a )); 4508return Ctrl_C ; 4509} 4510 4511/// @return true if curbuf is the cmdwin and we're not editing the command line. 4512bool is_in_cmdwin (void ) 4513FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 4514{ 4515return bt_cmdwin (curbuf )&& get_cmdline_type ()== NUL ; 4516} 4517 4518/// Get script string 4519/// 4520/// Used for commands which accept either `:command script` or 4521/// 4522/// :command << endmarker 4523/// script 4524/// endmarker 4525/// 4526/// @param eap Command being run. 4527/// @param[out] lenp Location where length of resulting string is saved. Will 4528/// be set to zero when skipping. 4529/// 4530/// @return [allocated] NULL or script. Does not show any error messages. 4531/// NULL is returned when skipping and on error. 4532char * script_get (exarg_T * const eap ,size_t * const lenp ) 4533FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_MALLOC 4534{ 4535char * cmd = eap -> arg ; 4536 4537if (cmd [0 ]!= '<' || cmd [1 ]!= '<' || eap -> ea_getline == NULL ) { 4538* lenp = strlen (eap -> arg ); 4539return eap -> skip ?NULL :xmemdupz (eap -> arg ,* lenp ); 4540 } 4541cmd += 2 ; 4542 4543garray_T ga = { .ga_data = NULL , .ga_len = 0 }; 4544 4545list_T * const l = heredoc_get (eap ,cmd , true); 4546if (l == NULL ) { 4547return NULL ; 4548 } 4549 4550if (!eap -> skip ) { 4551ga_init (& ga ,1 ,0x400 ); 4552 } 4553 4554TV_LIST_ITER_CONST (l ,li , { 4555if (!eap -> skip ) { 4556ga_concat (& ga ,tv_get_string (TV_LIST_ITEM_TV (li ))); 4557ga_append (& ga ,'\n' ); 4558 } 4559 }); 4560* lenp = (size_t )ga .ga_len ;// Set length without trailing NUL. 4561if (!eap -> skip ) { 4562ga_append (& ga ,NUL ); 4563 } 4564 4565tv_list_free (l ); 4566return (char * )ga .ga_data ; 4567} 4568 4569/// This function is used by f_input() and f_inputdialog() functions. The third 4570/// argument to f_input() specifies the type of completion to use at the 4571/// prompt. The third argument to f_inputdialog() specifies the value to return 4572/// when the user cancels the prompt. 4573void get_user_input (const typval_T * const argvars ,typval_T * const rettv ,const bool inputdialog , 4574const bool secret ) 4575FUNC_ATTR_NONNULL_ALL 4576{ 4577rettv -> v_type = VAR_STRING ; 4578rettv -> vval .v_string = NULL ; 4579 4580if (cmdpreview ) { 4581return ; 4582 } 4583 4584const char * prompt ; 4585const char * defstr = "" ; 4586typval_T * cancelreturn = NULL ; 4587typval_T cancelreturn_strarg2 = TV_INITIAL_VALUE ; 4588const char * xp_name = NULL ; 4589Callback input_callback = CALLBACK_INIT ; 4590char prompt_buf [NUMBUFLEN ]; 4591char defstr_buf [NUMBUFLEN ]; 4592char cancelreturn_buf [NUMBUFLEN ]; 4593char xp_name_buf [NUMBUFLEN ]; 4594char def [1 ]= {0 }; 4595if (argvars [0 ].v_type == VAR_DICT ) { 4596if (argvars [1 ].v_type != VAR_UNKNOWN ) { 4597emsg (_ ("E5050: {opts} must be the only argument" )); 4598return ; 4599 } 4600dict_T * const dict = argvars [0 ].vval .v_dict ; 4601prompt = tv_dict_get_string_buf_chk (dict ,S_LEN ("prompt" ),prompt_buf ,"" ); 4602if (prompt == NULL ) { 4603return ; 4604 } 4605defstr = tv_dict_get_string_buf_chk (dict ,S_LEN ("default" ),defstr_buf ,"" ); 4606if (defstr == NULL ) { 4607return ; 4608 } 4609dictitem_T * cancelreturn_di = tv_dict_find (dict ,S_LEN ("cancelreturn" )); 4610if (cancelreturn_di != NULL ) { 4611cancelreturn = & cancelreturn_di -> di_tv ; 4612 } 4613xp_name = tv_dict_get_string_buf_chk (dict ,S_LEN ("completion" ), 4614xp_name_buf ,def ); 4615if (xp_name == NULL ) {// error 4616return ; 4617 } 4618if (xp_name == def ) {// default to NULL 4619xp_name = NULL ; 4620 } 4621if (!tv_dict_get_callback (dict ,S_LEN ("highlight" ),& input_callback )) { 4622return ; 4623 } 4624 }else { 4625prompt = tv_get_string_buf_chk (& argvars [0 ],prompt_buf ); 4626if (prompt == NULL ) { 4627return ; 4628 } 4629if (argvars [1 ].v_type != VAR_UNKNOWN ) { 4630defstr = tv_get_string_buf_chk (& argvars [1 ],defstr_buf ); 4631if (defstr == NULL ) { 4632return ; 4633 } 4634if (argvars [2 ].v_type != VAR_UNKNOWN ) { 4635const char * const strarg2 = tv_get_string_buf_chk (& argvars [2 ],cancelreturn_buf ); 4636if (strarg2 == NULL ) { 4637return ; 4638 } 4639if (inputdialog ) { 4640cancelreturn_strarg2 .v_type = VAR_STRING ; 4641cancelreturn_strarg2 .vval .v_string = (char * )strarg2 ; 4642cancelreturn = & cancelreturn_strarg2 ; 4643 }else { 4644xp_name = strarg2 ; 4645 } 4646 } 4647 } 4648 } 4649 4650int xp_type = EXPAND_NOTHING ; 4651char * xp_arg = NULL ; 4652if (xp_name != NULL ) { 4653// input() with a third argument: completion 4654const int xp_namelen = (int )strlen (xp_name ); 4655 4656uint32_t argt = 0 ; 4657if (parse_compl_arg (xp_name ,xp_namelen ,& xp_type , 4658& argt ,& xp_arg )== FAIL ) { 4659return ; 4660 } 4661 } 4662 4663// Only the part of the message after the last NL is considered as 4664// prompt for the command line, unlsess cmdline is externalized 4665const char * p = prompt ; 4666if (!ui_has (kUICmdline )) { 4667const char * lastnl = strrchr (prompt ,'\n' ); 4668if (lastnl != NULL ) { 4669p = lastnl + 1 ; 4670msg_start (); 4671msg_clr_eos (); 4672msg_puts_len (prompt ,p - prompt ,get_echo_hl_id (), false); 4673msg_didout = false; 4674msg_starthere (); 4675 } 4676 } 4677cmdline_row = msg_row ; 4678 4679stuffReadbuffSpecial (defstr ); 4680 4681const int save_ex_normal_busy = ex_normal_busy ; 4682ex_normal_busy = 0 ; 4683atom_payload_start (); 4684rettv -> vval .v_string = getcmdline_prompt (secret ?NUL :'@' ,p ,get_echo_hl_id (), 4685xp_type ,xp_arg ,input_callback , false,NULL ); 4686atom_payload_end (); 4687ex_normal_busy = save_ex_normal_busy ; 4688callback_free (& input_callback ); 4689 4690if (rettv -> vval .v_string == NULL && cancelreturn != NULL ) { 4691tv_copy (cancelreturn ,rettv ); 4692 } 4693 4694xfree (xp_arg ); 4695 4696// Since the user typed this, no need to wait for return. 4697need_wait_return = false; 4698msg_didout = false; 4699} 4700 4701/// "wildtrigger()" function 4702void f_wildtrigger (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 4703{ 4704if (!(State & MODE_CMDLINE )|| char_avail () 4705|| wild_menu_showing 4706|| cmdline_pum_active ()) { 4707return ; 4708 } 4709 4710int cmd_type = get_cmdline_type (); 4711 4712if (cmd_type == ':' || cmd_type == '/' || cmd_type == '?' ) { 4713// Add K_WILD as a single special key 4714uint8_t key_string [4 ]; 4715key_string [0 ]= K_SPECIAL ; 4716key_string [1 ]= KS_EXTRA ; 4717key_string [2 ]= KE_WILD ; 4718key_string [3 ]= NUL ; 4719 4720// Insert it into the typeahead buffer 4721ins_typebuf ((char * )key_string ,REMAP_NONE ,0 , true, false); 4722 } 4723}