robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// message.c: functions for displaying messages on the command line 2 3#include <assert.h> 4#include <inttypes.h> 5#include <limits.h> 6#include <stdarg.h> 7#include <stdbool.h> 8#include <stddef.h> 9#include <stdio.h> 10#include <stdlib.h> 11#include <string.h> 12#include <uv.h> 13 14#include "klib/kvec.h" 15#include "nvim/api/private/defs.h" 16#include "nvim/api/private/helpers.h" 17#include "nvim/api/vim.h" 18#include "nvim/ascii_defs.h" 19#include "nvim/autocmd.h" 20#include "nvim/buffer_defs.h" 21#include "nvim/channel.h" 22#include "nvim/charset.h" 23#include "nvim/dialog.h" 24#include "nvim/drawscreen.h" 25#include "nvim/errors.h" 26#include "nvim/eval.h" 27#include "nvim/eval/typval.h" 28#include "nvim/eval/typval_defs.h" 29#include "nvim/eval/vars.h" 30#include "nvim/event/defs.h" 31#include "nvim/event/loop.h" 32#include "nvim/event/multiqueue.h" 33#include "nvim/ex_cmds_defs.h" 34#include "nvim/ex_docmd.h" 35#include "nvim/ex_eval.h" 36#include "nvim/ex_getln.h" 37#include "nvim/fileio.h" 38#include "nvim/garray.h" 39#include "nvim/garray_defs.h" 40#include "nvim/gettext_defs.h" 41#include "nvim/globals.h" 42#include "nvim/grid.h" 43#include "nvim/highlight.h" 44#include "nvim/highlight_defs.h" 45#include "nvim/highlight_group.h" 46#include "nvim/indent.h" 47#include "nvim/input.h" 48#include "nvim/keycodes.h" 49#include "nvim/log.h" 50#include "nvim/main.h" 51#include "nvim/mbyte.h" 52#include "nvim/mbyte_defs.h" 53#include "nvim/memory.h" 54#include "nvim/memory_defs.h" 55#include "nvim/message.h" 56#include "nvim/message_defs.h" 57#include "nvim/mouse.h" 58#include "nvim/option.h" 59#include "nvim/option_vars.h" 60#include "nvim/optionstr.h" 61#include "nvim/os/fs.h" 62#include "nvim/os/input.h" 63#include "nvim/os/os.h" 64#include "nvim/os/time.h" 65#include "nvim/pos_defs.h" 66#include "nvim/regexp.h" 67#include "nvim/register.h" 68#include "nvim/runtime.h" 69#include "nvim/runtime_defs.h" 70#include "nvim/state_defs.h" 71#include "nvim/strings.h" 72#include "nvim/types_defs.h" 73#include "nvim/ui.h" 74#include "nvim/ui_compositor.h" 75#include "nvim/ui_defs.h" 76#include "nvim/vim_defs.h" 77 78#include "options_keysets.generated.h" 79 80// To be able to scroll back at the "more" and "hit-enter" prompts we need to 81// store the displayed text and remember where screen lines start. 82typedef struct msgchunk_S msgchunk_T ; 83struct msgchunk_S { 84msgchunk_T * sb_next ; 85msgchunk_T * sb_prev ; 86char sb_eol ;// true when line ends after this text 87int sb_msg_col ;// column in which text starts 88int sb_hl_id ;// text highlight id 89char sb_text [];// text to be displayed 90}; 91 92static int confirm_msg_used = false;// displaying confirm_msg 93#include "message.c.generated.h" 94 95MessageHistoryEntry * msg_hist_last = NULL ;// Last message (extern for unittest) 96static MessageHistoryEntry * msg_hist_first = NULL ;// First message 97static MessageHistoryEntry * msg_hist_temp = NULL ;// First potentially temporary message 98static int msg_hist_len = 0 ; 99static int msg_hist_max = 500 ;// The default max value is 500 100 101#define PROGRESS_TARGET_CMD 0x01 102 103// 'messagesopt' items. Default: "hit-enter,history:500,progress:c". 104static bool msg_hit_enter = true; 105static int msg_wait = 0 ; 106static int progress_msg_target = PROGRESS_TARGET_CMD ; 107 108static FILE * verbose_fd = NULL ; 109static bool verbose_did_open = false; 110 111static bool keep_msg_more = false;// keep_msg was set by msgmore() 112 113// When writing messages to the screen, there are many different situations. 114// A number of variables is used to remember the current state: 115// msg_didany true when messages were written since the last time the 116// user reacted to a prompt. 117// Reset: After hitting a key for the hit-return prompt, 118// hitting <CR> for the command line or input(). 119// Set: When any message is written to the screen. 120// msg_didout true when something was written to the current line. 121// Reset: When advancing to the next line, when the current 122// text can be overwritten. 123// Set: When any message is written to the screen. 124// msg_nowait No extra delay for the last drawn message. 125// Used in normal_cmd() before the mode message is drawn. 126// emsg_on_display There was an error message recently. Indicates that there 127// should be a delay before redrawing. 128// msg_scroll The next message should not overwrite the current one. 129// msg_scrolled How many lines the screen has been scrolled (because of 130// messages). Used in update_screen() to scroll the screen 131// back. Incremented each time the screen scrolls a line. 132// msg_scrolled_ign true when msg_scrolled is non-zero and msg_puts_hl() 133// writes something without scrolling should not make 134// need_wait_return to be set. This is a hack to make ":ts" 135// work without an extra prompt. 136// lines_left Number of lines available for messages before the 137// more-prompt is to be given. -1 when not set. 138// need_wait_return true when the hit-return prompt is needed. 139// Reset: After giving the hit-return prompt, when the user 140// has answered some other prompt. 141// Set: When the ruler or typeahead display is overwritten, 142// scrolling the screen for some message. 143// keep_msg Message to be displayed after redrawing the screen, in 144// Normal mode main loop. 145// This is an allocated string or NULL when not used. 146 147// Extended msg state, currently used for external UIs with ext_messages 148static const char * msg_ext_kind = NULL ; 149static const char * msg_ext_trigger = NULL ; 150static MsgID msg_ext_id = { .type = kObjectTypeInteger , .data .integer = 1 }; 151static Array * msg_ext_chunks = NULL ; 152static garray_T msg_ext_last_chunk = GA_INIT (sizeof (char ),40 ); 153static sattr_T msg_ext_last_attr = -1 ; 154static int msg_ext_last_hl_id ; 155 156static bool msg_ext_history = false;///< message was added to history 157static bool msg_ext_append = false;///< message appended to previous message line 158 159static int msg_grid_pos_at_flush = 0 ; 160 161static int64_t msg_id_next = 1 ;///< message id to be allocated to next message 162 163/// Returns true if the given integer message-id was previously generated. 164bool msg_id_exists (int64_t id ) 165{ 166return id > 0 && id < msg_id_next ; 167} 168 169static void ui_ext_msg_set_pos (int row ,bool scrolled ) 170{ 171char buf [MAX_SCHAR_SIZE ]; 172size_t size = schar_get (buf ,curwin -> w_p_fcs_chars .msgsep ); 173ui_call_msg_set_pos (msg_grid .handle ,row ,scrolled , 174 (String ){ .data = buf , .size = size },msg_grid .zindex , 175 (int )msg_grid .comp_index ); 176msg_grid .pending_comp_index_update = false; 177} 178 179void msg_grid_set_pos (int row ,bool scrolled ) 180{ 181if (!msg_grid .throttled ) { 182ui_ext_msg_set_pos (row ,scrolled ); 183msg_grid_pos_at_flush = row ; 184 } 185msg_grid_pos = row ; 186if (msg_grid .chars ) { 187msg_grid_adj .row_offset = - row ; 188 } 189} 190 191bool msg_use_grid (void ) 192{ 193return default_grid .chars && !ui_has (kUIMessages ); 194} 195 196void msg_grid_validate (void ) 197{ 198grid_assign_handle (& msg_grid ); 199bool should_alloc = msg_use_grid (); 200int max_rows = Rows - (int )p_ch ; 201if (should_alloc && (msg_grid .rows != Rows || msg_grid .cols != Columns 202|| !msg_grid .chars )) { 203// TODO(bfredl): eventually should be set to "invalid". I e all callers 204// will use the grid including clear to EOS if necessary. 205grid_alloc (& msg_grid ,Rows ,Columns , false, true); 206msg_grid .zindex = kZIndexMessages ; 207 208xfree (msg_grid .dirty_col ); 209msg_grid .dirty_col = xcalloc ((size_t )Rows ,sizeof (* msg_grid .dirty_col )); 210 211// Tricky: allow resize while pager or ex mode is active 212int pos = (State & MODE_ASKMORE ) ?0 :MAX (max_rows - msg_scrolled ,0 ); 213msg_grid .throttled = false;// don't throttle in 'cmdheight' area 214msg_grid_set_pos (pos ,msg_scrolled ); 215ui_comp_put_grid (& msg_grid ,pos ,0 ,msg_grid .rows ,msg_grid .cols , 216 false, true); 217ui_call_grid_resize (msg_grid .handle ,msg_grid .cols ,msg_grid .rows ); 218 219msg_scrolled_at_flush = msg_scrolled ; 220msg_grid .mouse_enabled = false; 221msg_grid_adj .target = & msg_grid ; 222 }else if (!should_alloc && msg_grid .chars ) { 223ui_comp_remove_grid (& msg_grid ); 224grid_free (& msg_grid ); 225XFREE_CLEAR (msg_grid .dirty_col ); 226ui_call_grid_destroy (msg_grid .handle ); 227msg_grid .throttled = false; 228msg_grid_adj .row_offset = 0 ; 229msg_grid_adj .target = & default_grid ; 230redraw_cmdline = true; 231 }else if (msg_grid .chars && !msg_scrolled && msg_grid_pos != max_rows ) { 232int diff = msg_grid_pos - max_rows ; 233msg_grid_set_pos (max_rows , false); 234if (diff > 0 ) { 235grid_clear (& msg_grid_adj ,Rows - diff ,Rows ,0 ,Columns ,HL_ATTR (HLF_MSG )); 236 } 237 } 238 239if (msg_grid .chars && !msg_scrolled && cmdline_row < msg_grid_pos ) { 240// TODO(bfredl): this should already be the case, but fails in some 241// "batched" executions where compute_cmdrow() use stale positions or 242// something. 243cmdline_row = msg_grid_pos ; 244 } 245} 246 247/// Like msg() but keep it silent when 'verbosefile' is set. 248int verb_msg (const char * s ) 249{ 250verbose_enter (); 251int n = msg_keep (s ,0 , false, false); 252verbose_leave (); 253 254return n ; 255} 256 257/// Displays the string 's' on the status line 258/// When terminal not initialized (yet) printf("%s", ..) is used. 259/// 260/// @return true if wait_return() not called 261bool msg (const char * s ,const int hl_id ) 262FUNC_ATTR_NONNULL_ARG (1 ) 263{ 264return msg_keep (s ,hl_id , false, false); 265} 266 267/// Similar to msg_outtrans_len, but support newlines and tabs. 268void msg_multiline (String str ,int hl_id ,bool check_int ,bool hist ,bool * need_clear ) 269FUNC_ATTR_NONNULL_ALL 270{ 271const char * s = str .data ; 272const char * chunk = s ; 273while ((size_t )(s - str .data )< str .size ) { 274if (check_int && got_int ) { 275return ; 276 } 277if (* s == '\n' || * s == TAB || * s == '\r' || * s == BELL ) { 278// Print all chars before the delimiter 279msg_outtrans_len (chunk , (int )(s - chunk ),hl_id ,hist ); 280 281if (* s != TAB && * need_clear ) { 282msg_clr_eos (); 283* need_clear = false; 284 } 285if (* s == BELL ) { 286vim_beep (kOptBoFlagShell ); 287 }else { 288msg_putchar_hl ((uint8_t )(* s ),hl_id ); 289 } 290chunk = s + 1 ; 291 } 292s ++ ; 293 } 294 295// Print the remainder or emit empty event if entire message is empty. 296if (* chunk != NUL || chunk == str .data ) { 297msg_outtrans_len (chunk , (int )(str .size - (size_t )(chunk - str .data )),hl_id ,hist ); 298 } 299} 300 301// Ensure a single msg_show event, msg_list and history entry for entire multihl message. 302static int is_multihl = 0 ; 303 304/// Format a progress message, adding title and percent if given. 305/// 306/// @param hl_msg Message chunks 307/// @param msg_data Additional data for progress messages 308static bool format_progress_message (HlMessage * hl_msg ,MessageData * msg_data ) 309{ 310HlMessage updated_msg = KV_INITIAL_VALUE ; 311// progress messages are special. displayed as "title: percent% msg" 312if (msg_data -> title .size != 0 ) { 313// this block draws the "title:" before the progress-message 314int hl_id = 0 ; 315if (msg_data -> status .data == NULL ) { 316hl_id = 0 ; 317 }else if (strequal (msg_data -> status .data ,"success" )) { 318hl_id = syn_check_group ("OkMsg" ,STRLEN_LITERAL ("OkMsg" )); 319 }else if (strequal (msg_data -> status .data ,"failed" )) { 320hl_id = syn_check_group ("ErrorMsg" ,STRLEN_LITERAL ("ErrorMsg" )); 321 }else if (strequal (msg_data -> status .data ,"running" )) { 322hl_id = syn_check_group ("MoreMsg" ,STRLEN_LITERAL ("MoreMsg" )); 323 }else if (strequal (msg_data -> status .data ,"cancel" )) { 324hl_id = syn_check_group ("WarningMsg" ,STRLEN_LITERAL ("WarningMsg" )); 325 } 326kv_push (updated_msg , ((HlMessageChunk ){copy_string (msg_data -> title ,NULL ),hl_id })); 327kv_push (updated_msg , ((HlMessageChunk ){cstr_to_string (": " ),0 })); 328 } 329if (msg_data -> percent >=0 ) { 330char percent_buf [10 ]; 331vim_snprintf (percent_buf ,sizeof (percent_buf ),"%3ld%% " , (long )msg_data -> percent ); 332String percent = cstr_to_string (percent_buf ); 333int hl_id = syn_check_group ("WarningMsg" ,STRLEN_LITERAL ("WarningMsg" )); 334kv_push (updated_msg , ((HlMessageChunk ){percent ,hl_id })); 335 } 336 337if (kv_size (updated_msg )!= 0 ) { 338for (uint32_t i = 0 ;i < kv_size (* hl_msg );i ++ ) { 339HlMessageChunk chunk = kv_A (* hl_msg ,i ); 340kv_push (updated_msg , ((HlMessageChunk ){copy_string (chunk .text ,NULL ),chunk .hl_id })); 341 } 342* hl_msg = updated_msg ; 343return true; 344 } 345return false; 346} 347 348/// Print message chunks, each with their own highlight ID. 349/// 350/// @param hl_msg Message chunks 351/// @param kind Message kind (can be NULL to avoid setting kind) 352/// @param history Whether to add message to history 353/// @param err Whether to print message as an error 354/// @param msg_data Progress-message data 355MsgID msg_multihl (MsgID id ,HlMessage hl_msg ,const char * kind ,bool history ,bool err , 356MessageData * msg_data ,bool * needs_msg_clear ) 357{ 358// Message `id`: 359// - Nil: Generate a new Integer id. 360// - Integer: Existing id. 361// - String: User-defined id (new or existing). 362if (id .type == kObjectTypeNil ) { 363id = INTEGER_OBJ (msg_id_next ++ ); 364 }else if (id .type == kObjectTypeInteger && !msg_id_exists (id .data .integer )) { 365abort (); 366 } 367 368bool hl_msg_updated = false; 369// don't display progress message in cmd when target doesn't have cmd 370if (strequal (kind ,"progress" )) { 371do_autocmd_progress (id ,hl_msg ,msg_data ); 372if ((progress_msg_target & PROGRESS_TARGET_CMD )== 0 ) { 373* needs_msg_clear = true; 374return id ; 375 } 376if (msg_data && format_progress_message (& hl_msg ,msg_data )) { 377* needs_msg_clear = true; 378hl_msg_updated = true; 379 } 380 } 381 382no_wait_return ++ ; 383msg_start (); 384msg_clr_eos (); 385bool need_clear = false; 386if (kind != NULL ) { 387msg_ext_set_kind (kind ); 388 } 389msg_ext_skip_flush = true; 390msg_ext_id = id ; 391 392for (uint32_t i = 0 ;i < kv_size (hl_msg );i ++ ) { 393HlMessageChunk chunk = kv_A (hl_msg ,i ); 394is_multihl ++ ; 395if (err ) { 396emsg_multiline (chunk .text .data ,kind ,chunk .hl_id , true); 397 }else { 398msg_multiline (chunk .text ,chunk .hl_id , true, false,& need_clear ); 399 } 400assert (!ui_has (kUIMessages )|| kind == NULL || msg_ext_kind == kind ); 401 } 402 403if (history && kv_size (hl_msg )) { 404msg_hist_add_multihl (hl_msg , false); 405 } 406 407msg_ext_skip_flush = false; 408is_multihl = 0 ; 409no_wait_return -- ; 410msg_end (); 411 412if (hl_msg_updated && !(history && kv_size (hl_msg ))) { 413hl_msg_free (hl_msg ); 414 } 415// Release the id: it belongs to this message, and a String id only borrows the caller's storage 416// (often a stack buffer). Redundant unless nothing was emitted (e.g. 'msg_silent'). 417msg_ext_id = INTEGER_OBJ (msg_id_next ); 418return id ; 419} 420 421/// @param keep set keep_msg if it doesn't scroll 422bool msg_keep (const char * s ,int hl_id ,bool keep ,bool multiline ) 423FUNC_ATTR_NONNULL_ALL 424{ 425static int entered = 0 ; 426 427if (keep && multiline ) { 428// Not implemented. 'multiline' is only used by nvim-added messages, 429// which should avoid 'keep' behavior (just show the message at 430// the correct time already). 431abort (); 432 } 433 434// Skip messages not match ":filter pattern". 435// Don't filter when there is an error. 436if (!emsg_on_display && message_filtered (s )) { 437return true; 438 } 439 440if (hl_id == 0 ) { 441set_vim_var_string (VV_STATUSMSG ,s ,-1 ); 442 } 443 444// It is possible that displaying a messages causes a problem (e.g., 445// when redrawing the window), which causes another message, etc.. To 446// break this loop, limit the recursiveness to 3 levels. 447if (entered >=3 ) { 448return true; 449 } 450entered ++ ; 451 452// Add message to history unless it's a multihl, repeated kept or truncated message. 453if (!is_multihl 454&& (s != keep_msg 455|| (* s != '<' && msg_hist_last != NULL 456&& strcmp (s ,msg_hist_last -> msg .items [0 ].text .data )!= 0 ))) { 457msg_hist_add (s ,-1 ,hl_id ); 458 } 459 460if (!is_multihl ) { 461msg_start (); 462 } 463// Truncate the message if needed. 464char * buf = msg_strtrunc (s , false); 465if (buf != NULL ) { 466s = buf ; 467 } 468 469bool need_clear = true; 470if (multiline ) { 471msg_multiline (cstr_as_string (s ),hl_id , false, false,& need_clear ); 472 }else { 473msg_outtrans (s ,hl_id , false); 474 } 475if (need_clear ) { 476msg_clr_eos (); 477 } 478bool retval = true; 479if (!is_multihl ) { 480retval = msg_end (); 481 } 482 483if (keep && retval && vim_strsize (s )< (Rows - cmdline_row - 1 )* Columns + sc_col ) { 484set_keep_msg (s ,0 ); 485 } 486 487need_fileinfo = false; 488 489xfree (buf ); 490entered -- ; 491return retval ; 492} 493 494/// Truncate a string such that it can be printed without causing a scroll. 495/// 496/// @return an allocated string or NULL when no truncating is done. 497/// 498/// @param force always truncate 499char * msg_strtrunc (const char * s ,int force ) 500{ 501char * buf = NULL ; 502 503// May truncate message to avoid a hit-return prompt 504if ((!msg_scroll && !need_wait_return && shortmess (kShmTruncall ) 505&& msg_silent == 0 && !ui_has (kUIMessages )) 506|| force ) { 507int room ; 508int len = vim_strsize (s ); 509if (msg_scrolled != 0 ) { 510// Use all the columns. 511room = (Rows - msg_row )* Columns - 1 ; 512 }else { 513// Use up to 'showcmd' column. 514// In the case of ui2, we no longer need to avoid the "Press ENTER" prompt, but the message is 515// still kept under 1 line to avoid glitches. For example, when a long search term is 516// displayed that expands the cmdline, it will be immediately collapsed again when the search 517// count is displayed, which leads to flickering on each hit. 518int last_row = ui_has (kUIMessages ) ?Columns :sc_col - 1 ; 519room = (Rows - msg_row - 1 )* Columns + last_row ; 520 } 521if (len > room && room > 0 ) { 522// may have up to 18 bytes per cell (6 per char, up to two 523// composing chars) 524len = (room + 2 )* 18 ; 525buf = xmalloc ((size_t )len ); 526trunc_string (s ,buf ,room ,len ); 527 } 528 } 529return buf ; 530} 531 532/// Truncate a string "s" to "buf" with cell width "room". 533/// "s" and "buf" may be equal. 534void trunc_string (const char * s ,char * buf ,int room_in ,int buflen ) 535{ 536int room = room_in - 3 ;// "..." takes 3 chars 537int len = 0 ; 538int e ; 539int i ; 540int n ; 541 542if (* s == NUL ) { 543if (buflen > 0 ) { 544* buf = NUL ; 545 } 546return ; 547 } 548 549if (room_in < 3 ) { 550room = 0 ; 551 } 552int half = room /2 ; 553 554// First part: Start of the string. 555for (e = 0 ;len < half && e < buflen ;e ++ ) { 556if (s [e ]== NUL ) { 557// text fits without truncating! 558buf [e ]= NUL ; 559return ; 560 } 561n = ptr2cells (s + e ); 562if (len + n > half ) { 563break ; 564 } 565len += n ; 566buf [e ]= s [e ]; 567for (n = utfc_ptr2len (s + e );-- n > 0 ;) { 568if (++ e == buflen ) { 569break ; 570 } 571buf [e ]= s [e ]; 572 } 573 } 574 575// Last part: End of the string. 576half = i = (int )strlen (s ); 577while (true) { 578half = half - utf_head_off (s ,s + half - 1 )- 1 ; 579n = ptr2cells (s + half ); 580if (len + n > room || half == 0 ) { 581break ; 582 } 583len += n ; 584i = half ; 585 } 586 587if (i <=e + 3 ) { 588// text fits without truncating 589if (s != buf ) { 590len = (int )strlen (s ); 591if (len >=buflen ) { 592len = buflen - 1 ; 593 } 594len = len - e + 1 ; 595if (len < 1 ) { 596buf [e - 1 ]= NUL ; 597 }else { 598memmove (buf + e ,s + e , (size_t )len ); 599 } 600 } 601 }else if (e + 3 < buflen ) { 602// set the middle and copy the last part 603memmove (buf + e ,"..." ,3 ); 604len = (int )strlen (s + i )+ 1 ; 605if (len >=buflen - e - 3 ) { 606len = buflen - e - 3 - 1 ; 607 } 608memmove (buf + e + 3 ,s + i , (size_t )len ); 609buf [e + 3 + len - 1 ]= NUL ; 610 }else { 611// can't fit in the "...", just truncate it 612buf [buflen - 1 ]= NUL ; 613 } 614} 615 616/// Shows a printf-style message with highlight id. 617/// 618/// Note: Caller must check the resulting string is shorter than IOSIZE!!! 619/// 620/// @see semsg 621/// @see swmsg 622/// 623/// @param s printf-style format message 624int smsg (int hl_id ,const char * s , ...) 625FUNC_ATTR_PRINTF (2 ,3 ) 626{ 627va_list arglist ; 628 629va_start (arglist ,s ); 630vim_vsnprintf (IObuff ,IOSIZE ,s ,arglist ); 631va_end (arglist ); 632return msg (IObuff ,hl_id ); 633} 634 635int smsg_keep (int hl_id ,const char * s , ...) 636FUNC_ATTR_PRINTF (2 ,3 ) 637{ 638va_list arglist ; 639 640va_start (arglist ,s ); 641vim_vsnprintf (IObuff ,IOSIZE ,s ,arglist ); 642va_end (arglist ); 643return msg_keep (IObuff ,hl_id , true, false); 644} 645 646// Remember the last sourcing name/lnum used in an error message, so that it 647// isn't printed each time when it didn't change. 648static int last_sourcing_lnum = 0 ; 649static char * last_sourcing_name = NULL ; 650 651/// Reset the last used sourcing name/lnum. Makes sure it is displayed again 652/// for the next error message; 653void reset_last_sourcing (void ) 654{ 655XFREE_CLEAR (last_sourcing_name ); 656last_sourcing_lnum = 0 ; 657} 658 659/// @return true if "SOURCING_NAME" differs from "last_sourcing_name". 660static bool other_sourcing_name (void ) 661{ 662if (HAVE_SOURCING_INFO && SOURCING_NAME != NULL ) { 663if (last_sourcing_name != NULL ) { 664return strcmp (SOURCING_NAME ,last_sourcing_name )!= 0 ; 665 } 666return true; 667 } 668return false; 669} 670 671/// Get the message about the source, as used for an error message 672/// 673/// @return [allocated] String with room for one more character. NULL when no 674/// message is to be given. 675static char * get_emsg_source (void ) 676FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT 677{ 678if (HAVE_SOURCING_INFO && SOURCING_NAME != NULL && other_sourcing_name ()) { 679char * sname = estack_sfile (ESTACK_NONE ); 680char * tofree = sname ; 681 682if (sname == NULL ) { 683sname = SOURCING_NAME ; 684 } 685 686const char * const p = _ ("Error in %s:" ); 687const size_t buf_len = strlen (sname )+ strlen (p )+ 1 ; 688char * const buf = xmalloc (buf_len ); 689snprintf (buf ,buf_len ,p ,sname ); 690xfree (tofree ); 691return buf ; 692 } 693return NULL ; 694} 695 696/// Get the message about the source lnum, as used for an error message. 697/// 698/// @return [allocated] String with room for one more character. NULL when no 699/// message is to be given. 700static char * get_emsg_lnum (void ) 701FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT 702{ 703// lnum is 0 when executing a command from the command line 704// argument, we don't want a line number then 705if (SOURCING_NAME != NULL 706&& (other_sourcing_name ()|| SOURCING_LNUM != last_sourcing_lnum ) 707&& SOURCING_LNUM != 0 ) { 708const char * const p = _ ("line %4" PRIdLINENR ":" ); 709const size_t buf_len = 20 + strlen (p ); 710char * const buf = xmalloc (buf_len ); 711snprintf (buf ,buf_len ,p ,SOURCING_LNUM ); 712return buf ; 713 } 714return NULL ; 715} 716 717/// Display name and line number for the source of an error. 718/// Remember the file name and line number, so that for the next error the info 719/// is only displayed if it changed. 720void msg_source (int hl_id ) 721{ 722static bool recursive = false; 723 724// Bail out if something called here causes an error. 725if (recursive ) { 726return ; 727 } 728recursive = true; 729 730no_wait_return ++ ; 731char * p = get_emsg_source (); 732if (p != NULL ) { 733msg_scroll = true;// this will take more than one line 734msg (p ,hl_id ); 735xfree (p ); 736 } 737p = get_emsg_lnum (); 738if (p != NULL ) { 739msg (p ,HLF_N ); 740xfree (p ); 741last_sourcing_lnum = SOURCING_LNUM ;// only once for each line 742 } 743 744// remember the last sourcing name printed, also when it's empty 745if (SOURCING_NAME == NULL || other_sourcing_name ()) { 746XFREE_CLEAR (last_sourcing_name ); 747if (SOURCING_NAME != NULL ) { 748last_sourcing_name = xstrdup (SOURCING_NAME ); 749if (!redirecting ()) { 750msg_putchar_hl ('\n' ,hl_id ); 751 } 752 } 753 } 754no_wait_return -- ; 755 756recursive = false; 757} 758 759/// @return true if not giving error messages right now: 760/// If "emsg_off" is set: no error messages at the moment. 761/// If "msg" is in 'debug': do error message but without side effects. 762/// If "emsg_skip" is set: never do error messages. 763static int emsg_not_now (void ) 764{ 765if ((emsg_off > 0 && vim_strchr (p_debug ,'m' )== NULL 766&& vim_strchr (p_debug ,'t' )== NULL ) 767|| emsg_skip > 0 ) { 768return true; 769 } 770return false; 771} 772 773bool emsg_multiline (const char * s ,const char * kind ,int hl_id ,bool multiline ) 774{ 775bool ignore = false; 776 777// Skip this if not giving error messages at the moment. 778if (emsg_not_now ()) { 779return true; 780 } 781 782called_emsg ++ ; 783 784// If "emsg_severe" is true: When an error exception is to be thrown, 785// prefer this message over previous messages for the same command. 786bool severe = emsg_severe ; 787emsg_severe = false; 788 789if (!emsg_off || vim_strchr (p_debug ,'t' )!= NULL ) { 790// Cause a throw of an error exception if appropriate. Don't display 791// the error message in this case. (If no matching catch clause will 792// be found, the message will be displayed later on.) "ignore" is set 793// when the message should be ignored completely (used for the 794// interrupt message). 795if (cause_errthrow (s ,multiline ,is_multihl > 1 ,severe ,& ignore )) { 796if (!ignore ) { 797did_emsg ++ ; 798 } 799return true; 800 } 801 802if (in_assert_fails && emsg_assert_fails_msg == NULL ) { 803emsg_assert_fails_msg = xstrdup (s ); 804emsg_assert_fails_lnum = SOURCING_LNUM ; 805xfree (emsg_assert_fails_context ); 806emsg_assert_fails_context = xstrdup (SOURCING_NAME == NULL ?"" :SOURCING_NAME ); 807 } 808 809// set "v:errmsg", also when using ":silent! cmd" 810set_vim_var_string (VV_ERRMSG ,s ,-1 ); 811 812// When using ":silent! cmd" ignore error messages. 813// But do write it to the redirection file. 814if (emsg_silent != 0 ) { 815if (!emsg_noredir ) { 816msg_start (); 817char * p = get_emsg_source (); 818if (p != NULL ) { 819const size_t p_len = strlen (p ); 820p [p_len ]= '\n' ; 821redir_write (p , (ptrdiff_t )p_len + 1 ); 822xfree (p ); 823 } 824p = get_emsg_lnum (); 825if (p != NULL ) { 826const size_t p_len = strlen (p ); 827p [p_len ]= '\n' ; 828redir_write (p , (ptrdiff_t )p_len + 1 ); 829xfree (p ); 830 } 831redir_write (s , (ptrdiff_t )strlen (s )); 832 } 833 834// Log (silent) errors as debug messages. 835if (SOURCING_NAME != NULL && SOURCING_LNUM != 0 ) { 836DLOG ("(:silent) %s (%s (line %" PRIdLINENR "))" , 837s ,SOURCING_NAME ,SOURCING_LNUM ); 838 }else { 839DLOG ("(:silent) %s" ,s ); 840 } 841 842return true; 843 } 844 845// Log editor errors as INFO. 846if (SOURCING_NAME != NULL && SOURCING_LNUM != 0 ) { 847ILOG ("%s (%s (line %" PRIdLINENR "))" ,s ,SOURCING_NAME ,SOURCING_LNUM ); 848 }else { 849ILOG ("%s" ,s ); 850 } 851 852ex_exitval = 1 ; 853 854// Reset msg_silent, an error causes messages to be switched back on. 855msg_silent = 0 ; 856cmd_silent = false; 857 858if (global_busy ) {// break :global command 859global_busy ++ ; 860 } 861 862if (p_eb ) { 863beep_flush ();// also includes flush_buffers() 864 }else { 865flush_buffers (FLUSH_MINIMAL );// flush internal buffers 866 } 867did_emsg ++ ;// flag for DoOneCmd() 868 } 869 870emsg_on_display = true;// remember there is an error message 871if (msg_scrolled != 0 ) { 872need_wait_return = true;// needed in case emsg() is called after 873 }// wait_return() has reset need_wait_return 874// and a redraw is expected because 875// msg_scrolled is non-zero 876msg_ext_set_kind (kind ); 877 878// Display name and line number for the source of the error. 879msg_scroll = true; 880bool save_msg_skip_flush = msg_ext_skip_flush ; 881msg_ext_skip_flush = true; 882msg_source (hl_id ); 883 884// Display the error message itself. 885msg_nowait = false;// Wait for this msg. 886int rv = msg_keep (s ,hl_id , false,multiline ); 887msg_ext_skip_flush = save_msg_skip_flush ; 888return rv ; 889} 890 891/// emsg() - display an error message 892/// 893/// Rings the bell, if appropriate, and calls message() to do the real work 894/// When terminal not initialized (yet) fprintf(stderr, "%s", ..) is used. 895/// 896/// @return true if wait_return() not called 897bool emsg (const char * s ) 898{ 899return emsg_multiline (s ,"emsg" ,HLF_E , false); 900} 901 902void emsg_invreg (int name ) 903{ 904semsg (_ ("E354: Invalid register name: '%s'" ),transchar_buf (NULL ,name )); 905} 906 907/// Print an error message with unknown number of arguments 908/// 909/// @return whether the message was displayed 910bool semsg (const char * const fmt , ...) 911FUNC_ATTR_PRINTF (1 ,2 ) 912{ 913bool ret ; 914 915va_list ap ; 916va_start (ap ,fmt ); 917ret = semsgv (fmt ,ap ); 918va_end (ap ); 919 920return ret ; 921} 922 923#define MULTILINE_BUFSIZE 8192 924 925bool semsg_multiline (const char * kind ,const char * const fmt , ...) 926{ 927bool ret ; 928va_list ap ; 929 930static char errbuf [MULTILINE_BUFSIZE ]; 931if (emsg_not_now ()) { 932return true; 933 } 934 935va_start (ap ,fmt ); 936vim_vsnprintf (errbuf ,sizeof (errbuf ),fmt ,ap ); 937va_end (ap ); 938 939ret = emsg_multiline (errbuf ,kind ,HLF_E , true); 940 941return ret ; 942} 943 944/// Print an error message with unknown number of arguments 945static bool semsgv (const char * fmt ,va_list ap ) 946{ 947static char errbuf [IOSIZE ]; 948if (emsg_not_now ()) { 949return true; 950 } 951 952vim_vsnprintf (errbuf ,sizeof (errbuf ),fmt ,ap ); 953 954return emsg (errbuf ); 955} 956 957/// Same as emsg(...), but abort on error when ABORT_ON_INTERNAL_ERROR is 958/// defined. It is used for internal errors only, so that they can be 959/// detected when fuzzing vim. 960void iemsg (const char * s ) 961{ 962if (emsg_not_now ()) { 963return ; 964 } 965 966emsg (s ); 967#ifdef ABORT_ON_INTERNAL_ERROR 968set_vim_var_string (VV_ERRMSG ,s ,-1 ); 969msg_putchar ('\n' );// avoid overwriting the error message 970ui_flush (); 971abort (); 972#endif 973} 974 975/// Same as semsg(...) but abort on error when ABORT_ON_INTERNAL_ERROR is 976/// defined. It is used for internal errors only, so that they can be 977/// detected when fuzzing vim. 978void siemsg (const char * s , ...) 979{ 980if (emsg_not_now ()) { 981return ; 982 } 983 984va_list ap ; 985va_start (ap ,s ); 986semsgv (s ,ap ); 987va_end (ap ); 988#ifdef ABORT_ON_INTERNAL_ERROR 989msg_putchar ('\n' );// avoid overwriting the error message 990ui_flush (); 991abort (); 992#endif 993} 994 995/// Give an "Internal error" message. 996void internal_error (const char * where ) 997{ 998siemsg (_ (e_intern2 ),where ); 999} 1000 1001static void msg_semsg_event (void ** argv ) 1002{ 1003char * s = argv [0 ]; 1004emsg (s ); 1005xfree (s ); 1006} 1007 1008void msg_schedule_semsg (const char * const fmt , ...) 1009FUNC_ATTR_PRINTF (1 ,2 ) 1010{ 1011va_list ap ; 1012va_start (ap ,fmt ); 1013vim_vsnprintf (IObuff ,IOSIZE ,fmt ,ap ); 1014va_end (ap ); 1015 1016char * s = xstrdup (IObuff ); 1017loop_schedule_deferred (& main_loop ,event_create (msg_semsg_event ,s )); 1018} 1019 1020static void msg_semsg_multiline_event (void ** argv ) 1021{ 1022char * s = argv [0 ]; 1023emsg_multiline (s ,"emsg" ,HLF_E , true); 1024xfree (s ); 1025} 1026 1027void msg_schedule_semsg_multiline (const char * const fmt , ...) 1028{ 1029va_list ap ; 1030va_start (ap ,fmt ); 1031vim_vsnprintf (IObuff ,IOSIZE ,fmt ,ap ); 1032va_end (ap ); 1033 1034char * s = xstrdup (IObuff ); 1035loop_schedule_deferred (& main_loop ,event_create (msg_semsg_multiline_event ,s )); 1036} 1037 1038/// Like msg(), but truncate to a single line if p_shm contains 't', or when 1039/// "force" is true. This truncates in another way as for normal messages. 1040/// Careful: The string may be changed by msg_may_trunc()! 1041/// 1042/// @return a pointer to the printed message, if wait_return() not called. 1043char * msg_trunc (char * s ,bool force ,int hl_id ) 1044{ 1045// Add message to history before truncating. 1046msg_hist_add (s ,-1 ,hl_id ); 1047 1048char * ts = msg_may_trunc (force ,s ); 1049 1050msg_hist_off = true; 1051bool n = msg (ts ,hl_id ); 1052msg_hist_off = false; 1053 1054if (n ) { 1055return ts ; 1056 } 1057return NULL ; 1058} 1059 1060/// Check if message "s" should be truncated at the start (for filenames). 1061/// 1062/// @return a pointer to where the truncated message starts. 1063/// 1064/// @note: May change the message by replacing a character with '<'. 1065char * msg_may_trunc (bool force ,char * s ) 1066{ 1067if (ui_has (kUIMessages )) { 1068return s ; 1069 } 1070 1071// If something unexpected happened "room" may be negative, check for that 1072// just in case. 1073int room = (Rows - cmdline_row - 1 )* Columns + sc_col - 1 ; 1074if (room > 0 1075&& (force || shortmess (kShmTrunc )) 1076&& (int )strlen (s )- room > 0 ) { 1077int size = vim_strsize (s ); 1078 1079// There may be room anyway when there are multibyte chars. 1080if (size <=room ) { 1081return s ; 1082 } 1083int n ; 1084for (n = 0 ;size >=room ;) { 1085size -= utf_ptr2cells (s + n ); 1086n += utfc_ptr2len (s + n ); 1087 } 1088n -- ; 1089s += n ; 1090* s = '<' ; 1091 } 1092return s ; 1093} 1094 1095/// Shows a progress-message. A non-"running" `status` ends the message and announces the 1096/// progress task as "done". 1097/// 1098/// @param s Message text. NULL ends the message without showing anything. 1099/// @param err Show as an error message. 1100char * msg_progress (char * s ,char * id ,char * status ,int hl_id ,bool hist ,bool trunc ,bool err ) 1101{ 1102bool clear = false; 1103MessageData data = { 1104 .source = cstr_as_string ("nvim" ), 1105 .status = cstr_as_string (status ), 1106 .percent = -1 , 1107 }; 1108HlMessage chunks = KV_INITIAL_VALUE ; 1109if (s != NULL ) { 1110if (hist && (!trunc || ui_has (kUIMessages ))) { 1111msg_hist_add (s ,-1 ,0 ); 1112 } 1113if (trunc ) { 1114s = msg_may_trunc (false,s ); 1115 } 1116kv_push (chunks , ((HlMessageChunk ){cstr_as_string (s ),hl_id })); 1117 } 1118msg_ext_no_fast (); 1119msg_multihl (CSTR_AS_OBJ (id ),chunks ,"progress" , false,err ,& data ,& clear ); 1120kv_destroy (chunks ); 1121ui_flush (); 1122return s ; 1123} 1124 1125void hl_msg_free (HlMessage hl_msg ) 1126{ 1127for (size_t i = 0 ;i < kv_size (hl_msg );i ++ ) { 1128xfree (kv_A (hl_msg ,i ).text .data ); 1129 } 1130kv_destroy (hl_msg ); 1131} 1132 1133/// Add the message at the end of the history 1134/// 1135/// @param[in] len Length of s or -1. 1136static void msg_hist_add (const char * s ,int len ,int hl_id ) 1137{ 1138String text = { .size = len < 0 ?strlen (s ) : (size_t )len }; 1139// Remove leading and trailing newlines. 1140while (text .size > 0 && * s == '\n' ) { 1141text .size -- ; 1142s ++ ; 1143 } 1144while (text .size > 0 && s [text .size - 1 ]== '\n' ) { 1145text .size -- ; 1146 } 1147if (text .size == 0 ) { 1148return ; 1149 } 1150text .data = xmemdupz (s ,text .size ); 1151 1152HlMessage msg = KV_INITIAL_VALUE ; 1153kv_push (msg , ((HlMessageChunk ){text ,hl_id })); 1154msg_hist_add_multihl (msg , false); 1155} 1156 1157static bool do_clear_hist_temp = true; 1158 1159void do_autocmd_progress (MsgID msg_id ,HlMessage msg ,MessageData * msg_data ) 1160{ 1161if (!has_event (EVENT_PROGRESS )) { 1162return ; 1163 } 1164 1165MAXSIZE_TEMP_DICT (data ,7 ); 1166ArrayOf (String )messages = ARRAY_DICT_INIT ; 1167for (size_t i = 0 ;i < msg .size ;i ++ ) { 1168ADD (messages ,STRING_OBJ (msg .items [i ].text )); 1169 } 1170 1171PUT_C (data ,"id" ,OBJECT_OBJ (msg_id )); 1172PUT_C (data ,"text" ,ARRAY_OBJ (messages )); 1173if (msg_data != NULL ) { 1174if (msg_data -> percent >=0 ) { 1175// If percent=nil we omit it, it means "indeterminate progress". #39029 1176PUT_C (data ,"percent" ,INTEGER_OBJ (msg_data -> percent )); 1177 } 1178PUT_C (data ,"source" ,STRING_OBJ (msg_data -> source )); 1179PUT_C (data ,"status" ,STRING_OBJ (msg_data -> status )); 1180PUT_C (data ,"title" ,STRING_OBJ (msg_data -> title )); 1181PUT_C (data ,"data" ,DICT_OBJ (msg_data -> data )); 1182 } 1183 1184apply_autocmds_group (EVENT_PROGRESS , 1185 (msg_data && msg_data -> source .size > 0 ) ?msg_data -> source .data :"" ,NULL , 1186 true, 1187AUGROUP_ALL ,NULL ,curwin ,NULL ,& DICT_OBJ (data ), false); 1188kv_destroy (messages ); 1189} 1190 1191static void msg_hist_add_multihl (HlMessage msg ,bool temp ) 1192{ 1193if (do_clear_hist_temp ) { 1194msg_hist_clear_temp (); 1195do_clear_hist_temp = false; 1196 } 1197 1198if (msg_hist_off || msg_silent != 0 ) { 1199hl_msg_free (msg ); 1200return ; 1201 } 1202 1203// Allocate an entry and add the message at the end of the history. 1204MessageHistoryEntry * entry = xmalloc (sizeof (MessageHistoryEntry )); 1205entry -> msg = msg ; 1206entry -> temp = temp ; 1207entry -> kind = msg_ext_kind ?xstrdup (msg_ext_kind ) :NULL ; 1208entry -> prev = msg_hist_last ; 1209entry -> next = NULL ; 1210// NOTE: this does not encode if the message was actually appended to the 1211// previous entry in the message history. However append is currently only 1212// true for :echon, which is stored in the history as a temporary entry for 1213// "g<" where it is guaranteed to be after the entry it was appended to. 1214entry -> append = msg_ext_append ; 1215 1216if (msg_hist_first == NULL ) { 1217msg_hist_first = entry ; 1218 } 1219if (msg_hist_last != NULL ) { 1220msg_hist_last -> next = entry ; 1221 } 1222if (msg_hist_temp == NULL ) { 1223msg_hist_temp = entry ; 1224 } 1225 1226msg_hist_len += !temp ; 1227msg_hist_last = entry ; 1228msg_ext_history = true; 1229 1230msg_hist_clear (msg_hist_max ); 1231} 1232 1233static void msg_hist_free_msg (MessageHistoryEntry * entry ) 1234{ 1235if (entry -> next == NULL ) { 1236msg_hist_last = entry -> prev ; 1237 }else { 1238entry -> next -> prev = entry -> prev ; 1239 } 1240if (entry -> prev == NULL ) { 1241msg_hist_first = entry -> next ; 1242 }else { 1243entry -> prev -> next = entry -> next ; 1244 } 1245if (entry == msg_hist_temp ) { 1246msg_hist_temp = entry -> next ; 1247 } 1248hl_msg_free (entry -> msg ); 1249xfree (entry -> kind ); 1250xfree (entry ); 1251} 1252 1253/// Delete oldest messages from the history until there are "keep" messages. 1254void msg_hist_clear (int keep ) 1255{ 1256while (msg_hist_len > keep || (keep == 0 && msg_hist_first != NULL )) { 1257msg_hist_len -= !msg_hist_first -> temp ; 1258msg_hist_free_msg (msg_hist_first ); 1259 } 1260} 1261 1262void msg_hist_clear_temp (void ) 1263{ 1264while (msg_hist_temp != NULL ) { 1265MessageHistoryEntry * next = msg_hist_temp -> next ; 1266if (msg_hist_temp -> temp ) { 1267msg_hist_free_msg (msg_hist_temp ); 1268 } 1269msg_hist_temp = next ; 1270 } 1271} 1272 1273int messagesopt_changed (void ) 1274{ 1275OptKeyDict_mopt * v = opt_keyset (p_mopt ,kOptMessagesopt ,NULL ); 1276 1277// Either "wait" or "hit-enter" is required; "history" always. 1278if ((!v -> hit_enter && !HAS_KEY (v ,mopt ,wait ))|| !HAS_KEY (v ,mopt ,history )) { 1279return FAIL ; 1280 } 1281// "history" and "wait" must be <= 10000; "maxheight" is a percentage. 1282if (v -> history > 10000 || v -> wait > 10000 || v -> maxheight > 100 ) { 1283return FAIL ; 1284 } 1285 1286msg_hit_enter = v -> hit_enter ; 1287msg_wait = (int )v -> wait ; 1288progress_msg_target = strequal (v -> progress ,"c" ) ?PROGRESS_TARGET_CMD :0 ; 1289msg_hist_max = (int )v -> history ; 1290msg_hist_clear (msg_hist_max ); 1291 1292return OK ; 1293} 1294 1295/// :messages command implementation 1296void ex_messages (exarg_T * eap ) 1297FUNC_ATTR_NONNULL_ALL 1298{ 1299if (strcmp (eap -> arg ,"clear" )== 0 ) { 1300msg_hist_clear (eap -> addr_count ?eap -> line2 :0 ); 1301return ; 1302 } 1303 1304if (* eap -> arg != NUL ) { 1305emsg (_ (e_invarg )); 1306return ; 1307 } 1308 1309Array entries = ARRAY_DICT_INIT ; 1310MessageHistoryEntry * p = eap -> skip ?msg_hist_temp :msg_hist_first ; 1311int skip = eap -> addr_count ? (msg_hist_len - eap -> line2 ) :0 ; 1312for (;p != NULL ;p = p -> next ) { 1313// Skip over count or temporary "g<" messages. 1314if ((p -> temp && !eap -> skip )|| skip -- > 0 ) { 1315continue ; 1316 } 1317if (ui_has (kUIMessages )&& !msg_silent ) { 1318Array entry = ARRAY_DICT_INIT ; 1319ADD (entry ,CSTR_TO_OBJ (p -> kind )); 1320Array content = ARRAY_DICT_INIT ; 1321for (uint32_t i = 0 ;i < kv_size (p -> msg );i ++ ) { 1322HlMessageChunk chunk = kv_A (p -> msg ,i ); 1323Array content_entry = ARRAY_DICT_INIT ; 1324ADD (content_entry ,INTEGER_OBJ (chunk .hl_id ?syn_id2attr (chunk .hl_id ) :0 )); 1325ADD (content_entry ,STRING_OBJ (copy_string (chunk .text ,NULL ))); 1326ADD (content_entry ,INTEGER_OBJ (chunk .hl_id )); 1327ADD (content ,ARRAY_OBJ (content_entry )); 1328 } 1329ADD (entry ,ARRAY_OBJ (content )); 1330ADD (entry ,BOOLEAN_OBJ (p -> append )); 1331ADD (entries ,ARRAY_OBJ (entry )); 1332 } 1333if (redirecting ()|| !ui_has (kUIMessages )) { 1334msg_silent += ui_has (kUIMessages ); 1335bool needs_clear = false; 1336msg_multihl (NIL ,p -> msg ,p -> kind , false, false,NULL ,& needs_clear ); 1337msg_silent -= ui_has (kUIMessages ); 1338 } 1339 } 1340if (kv_size (entries )> 0 ) { 1341ui_call_msg_history_show (entries ,eap -> skip != 0 ); 1342api_free_array (entries ); 1343 } 1344} 1345 1346/// Call this after prompting the user. This will avoid a hit-return message 1347/// and a delay. 1348void msg_end_prompt (void ) 1349{ 1350need_wait_return = false; 1351emsg_on_display = false; 1352cmdline_row = msg_row ; 1353msg_col = 0 ; 1354msg_clr_eos (); 1355lines_left = -1 ; 1356} 1357 1358/// Wait for the user to hit a key (normally Enter) 1359/// 1360/// @param redraw if true, redraw the entire screen UPD_NOT_VALID 1361/// if false, do a normal redraw 1362/// if -1, don't redraw at all 1363void wait_return (int redraw ) 1364{ 1365int c ; 1366int had_got_int ; 1367FILE * save_scriptout ; 1368 1369if (redraw == true) { 1370redraw_all_later (UPD_NOT_VALID ); 1371 } 1372 1373if (ui_has (kUIMessages )) { 1374prompt_for_input ("Press any key to continue" ,HLF_M , true,NULL ); 1375return ; 1376 } 1377 1378// If using ":silent cmd", don't wait for a return. Also don't set 1379// need_wait_return to do it later. 1380if (msg_silent != 0 ) { 1381return ; 1382 } 1383 1384if (headless_mode && !ui_active ()) { 1385return ; 1386 } 1387 1388// When inside vgetc(), we can't wait for a typed character at all. 1389// With the global command (and some others) we only need one return at 1390// the end. Adjust cmdline_row to avoid the next message overwriting the 1391// last one. 1392if (vgetc_busy > 0 ) { 1393return ; 1394 } 1395need_wait_return = true; 1396if (no_wait_return ) { 1397cmdline_row = msg_row ; 1398return ; 1399 } 1400 1401redir_off = true;// don't redirect this message 1402int oldState = State ; 1403if (quit_more ) { 1404c = CAR ;// just pretend CR was hit 1405quit_more = false; 1406got_int = false; 1407 }else if (!stuff_empty ()) { 1408// When there are stuffed characters, the next stuffed character will 1409// dismiss the hit-enter prompt immediately and have to be put back, so 1410// instead just don't show the hit-enter prompt at all. 1411c = CAR ; 1412 }else { 1413State = MODE_HITRETURN ; 1414setmouse (); 1415cmdline_row = msg_row ; 1416// Avoid the sequence that the user types ":" at the hit-return prompt 1417// to start an Ex command, but the file-changed dialog gets in the 1418// way. 1419if (need_check_timestamps ) { 1420check_timestamps (false); 1421 } 1422 1423// if cmdheight=0, we need to scroll in the first line of msg_grid upon the screen 1424if (p_ch == 0 && !ui_has (kUIMessages )&& !msg_scrolled ) { 1425msg_grid_validate (); 1426msg_scroll_up (false, true); 1427msg_scrolled ++ ; 1428cmdline_row = Rows - 1 ; 1429 } 1430 1431if (msg_hit_enter ) { 1432hit_return_msg (true); 1433 1434do { 1435// Remember "got_int", if it is set vgetc() probably returns a 1436// CTRL-C, but we need to loop then. 1437had_got_int = got_int ; 1438 1439// Don't do mappings here, we put the character back in the 1440// typeahead buffer. 1441no_mapping ++ ; 1442allow_keys ++ ; 1443 1444// Temporarily disable Recording. If Recording is active, the 1445// character will be recorded later, since it will be added to the 1446// typebuf after the loop 1447const int save_reg_recording = reg_recording ; 1448save_scriptout = scriptout ; 1449reg_recording = 0 ; 1450scriptout = NULL ; 1451c = safe_vgetc (); 1452if (had_got_int && !global_busy ) { 1453got_int = false; 1454 } 1455no_mapping -- ; 1456allow_keys -- ; 1457reg_recording = save_reg_recording ; 1458scriptout = save_scriptout ; 1459 1460// Allow scrolling back in the messages. 1461// Also accept scroll-down commands when messages fill the screen, 1462// to avoid that typing one 'j' too many makes the messages 1463// disappear. 1464if (KeyTyped && p_more ) { 1465if (c == 'b' || c == Ctrl_B || c == 'k' || c == 'u' || c == 'g' 1466|| c == K_UP || c == K_PAGEUP ) { 1467if (msg_scrolled > Rows ) { 1468// scroll back to show older messages 1469do_more_prompt (c ); 1470 }else { 1471msg_didout = false; 1472c = K_IGNORE ; 1473msg_col = 0 ; 1474 } 1475if (quit_more ) { 1476c = CAR ;// just pretend CR was hit 1477quit_more = false; 1478got_int = false; 1479 }else if (c != K_IGNORE ) { 1480c = K_IGNORE ; 1481hit_return_msg (false); 1482 } 1483 }else if (msg_scrolled > Rows - 2 1484&& (c == 'j' || c == 'd' || c == 'f' || c == Ctrl_F 1485|| c == K_DOWN || c == K_PAGEDOWN )) { 1486c = K_IGNORE ; 1487 } 1488 } 1489 }while ((had_got_int && c == Ctrl_C ) 1490|| c == K_IGNORE 1491|| c == K_LEFTDRAG || c == K_LEFTRELEASE 1492|| c == K_MIDDLEDRAG || c == K_MIDDLERELEASE 1493|| c == K_RIGHTDRAG || c == K_RIGHTRELEASE 1494|| c == K_MOUSELEFT || c == K_MOUSERIGHT 1495|| c == K_MOUSEDOWN || c == K_MOUSEUP 1496|| c == K_MOUSEMOVE ); 1497os_breakcheck (); 1498 1499// Avoid that the mouse-up event causes visual mode to start. 1500if (c == K_LEFTMOUSE || c == K_MIDDLEMOUSE || c == K_RIGHTMOUSE 1501|| c == K_X1MOUSE || c == K_X2MOUSE ) { 1502jump_to_mouse (MOUSE_SETPOS ,NULL ,0 ); 1503 }else if (!KeyTyped 1504|| (vim_strchr ("\r\n " ,c )== NULL && c != Ctrl_C && c != 'q' )) { 1505// Put the character back in the typeahead buffer. Don't use the 1506// stuff buffer, because lmaps wouldn't work. 1507requeue_key (vgetc_char ,vgetc_mod_mask ,0 , 1508// Recording was suppressed around safe_vgetc() above. 1509 false); 1510do_redraw = true;// need a redraw even though there is typeahead 1511 } 1512 }else { 1513c = CAR ; 1514// Wait to allow the user to verify the output. 1515do_sleep (msg_wait , true); 1516 } 1517 } 1518redir_off = false; 1519 1520// If the user hits ':', '?' or '/' we get a command line from the next 1521// line. 1522if (c == ':' || c == '?' || c == '/' ) { 1523cmdline_row = msg_row ; 1524skip_redraw = true;// skip redraw once 1525do_redraw = false; 1526 } 1527 1528// If the screen size changed screen_resize() will redraw the screen. 1529// Otherwise the screen is only redrawn if 'redraw' is set and no ':' 1530// typed. 1531int tmpState = State ; 1532State = oldState ;// restore State before screen_resize() 1533setmouse (); 1534msg_check (); 1535need_wait_return = false; 1536did_wait_return = true; 1537emsg_on_display = false;// can delete error message now 1538lines_left = -1 ;// reset lines_left at next msg_start() 1539reset_last_sourcing (); 1540if (keep_msg != NULL && vim_strsize (keep_msg ) >= 1541 (Rows - cmdline_row - 1 )* Columns + sc_col ) { 1542XFREE_CLEAR (keep_msg );// don't redisplay message, it's too long 1543 } 1544 1545if (tmpState == MODE_SETWSIZE ) {// got resize event while in vgetc() 1546ui_refresh (); 1547 }else if (!skip_redraw ) { 1548if (redraw == true|| (msg_scrolled != 0 && redraw != -1 )) { 1549redraw_later (curwin ,UPD_VALID ); 1550 } 1551 } 1552} 1553 1554/// Write the hit-return prompt. 1555/// 1556/// @param newline_sb if starting a new line, add it to the scrollback. 1557static void hit_return_msg (bool newline_sb ) 1558{ 1559int save_p_more = p_more ; 1560 1561if (!newline_sb ) { 1562p_more = false; 1563 } 1564if (msg_didout ) {// start on a new line 1565msg_putchar ('\n' ); 1566 } 1567p_more = false;// don't want to see this message when scrolling back 1568if (got_int ) { 1569msg_puts (_ ("Interrupt: " )); 1570 } 1571 1572msg_puts_hl (_ ("Press ENTER or type command to continue" ),HLF_R , false); 1573if (!msg_use_printf ()) { 1574msg_clr_eos (); 1575 } 1576p_more = save_p_more ; 1577} 1578 1579/// Set "keep_msg" to "s". Free the old value and check for NULL pointer. 1580void set_keep_msg (const char * s ,int hl_id ) 1581{ 1582// Kept message is not cleared and re-emitted with ext_messages: #20416. 1583if (ui_has (kUIMessages )) { 1584return ; 1585 } 1586 1587xfree (keep_msg ); 1588if (s != NULL && msg_silent == 0 ) { 1589keep_msg = xstrdup (s ); 1590 }else { 1591keep_msg = NULL ; 1592 } 1593keep_msg_more = false; 1594keep_msg_hl_id = hl_id ; 1595} 1596 1597/// Return true if printing messages should currently be done. 1598bool messaging (void ) 1599{ 1600// TODO(bfredl): with general support for "async" messages with p_ch, 1601// this should be re-enabled. 1602return !(p_lz && char_avail ()&& !KeyTyped )&& (p_ch > 0 || ui_has (kUIMessages )); 1603} 1604 1605void msgmore (int n ) 1606{ 1607int pn ; 1608 1609if (global_busy // no messages now, wait until global is finished 1610|| !messaging ()) {// 'lazyredraw' set, don't do messages now 1611return ; 1612 } 1613 1614// We don't want to overwrite another important message, but do overwrite 1615// a previous "more lines" or "fewer lines" message, so that "5dd" and 1616// then "put" reports the last action. 1617if (keep_msg != NULL && !keep_msg_more ) { 1618return ; 1619 } 1620 1621pn = abs (n ); 1622 1623if (pn > p_report ) { 1624if (n > 0 ) { 1625vim_snprintf (msg_buf ,MSG_BUF_LEN , 1626NGETTEXT ("%d more line" ,"%d more lines" ,pn ), 1627pn ); 1628 }else { 1629vim_snprintf (msg_buf ,MSG_BUF_LEN , 1630NGETTEXT ("%d line less" ,"%d fewer lines" ,pn ), 1631pn ); 1632 } 1633if (got_int ) { 1634xstrlcat (msg_buf ,_ (" (Interrupted)" ),MSG_BUF_LEN ); 1635 } 1636if (msg (msg_buf ,0 )) { 1637set_keep_msg (msg_buf ,0 ); 1638keep_msg_more = true; 1639 } 1640 } 1641} 1642 1643static int redir_col = 0 ;// Message column used in redir_write(). 1644void msg_ext_set_kind (const char * msg_kind ) 1645{ 1646// Don't change the label of an existing batch: 1647msg_ext_ui_flush (); 1648 1649// TODO(bfredl): would be nice to avoid dynamic scoping, but that would 1650// need refactoring the msg_ interface to not be "please pretend nvim is 1651// a terminal for a moment" 1652msg_ext_kind = msg_kind ; 1653 1654// Need to reset the redirection column at the start of a message, for which 1655// leading newlines are responsible without kUIMessages. Unrelated to setting 1656// the kind but this is called more consistently at the start of a message 1657// than msg_start() at this point. 1658redir_col = msg_ext_append ?redir_col :0 ; 1659 1660if (strcmp ("list_cmd" ,msg_kind )== 0 ) { 1661msg_ext_no_fast (); 1662 } 1663} 1664 1665void msg_ext_set_append (bool append ) 1666{ 1667msg_ext_ui_flush (); 1668msg_ext_append = append ; 1669} 1670 1671void msg_ext_set_trigger (const char * trigger ) 1672{ 1673msg_ext_ui_flush (); 1674msg_ext_trigger = trigger ; 1675} 1676 1677// Should be executed at all callsites emitting non-internal messages. 1678void msg_ext_no_fast (void ) 1679{ 1680msg_ext_ui_flush (); 1681msg_ext_fast = false; 1682} 1683 1684/// Prepare for outputting characters in the command line. 1685void msg_start (void ) 1686{ 1687bool did_return = false; 1688 1689msg_row = MAX (msg_row ,cmdline_row ); 1690 1691if (!msg_silent ) { 1692XFREE_CLEAR (keep_msg );// don't display old message now 1693need_fileinfo = false; 1694 } 1695 1696if (need_highlight_changed ) { 1697highlight_changed (); 1698 } 1699 1700if (need_clr_eos || (p_ch == 0 && redrawing_cmdline )) { 1701// Halfway an ":echo" command and getting an (error) message: clear 1702// any text from the command. 1703need_clr_eos = false; 1704msg_clr_eos (); 1705 } 1706 1707// if cmdheight=0, we need to scroll in the first line of msg_grid upon the screen 1708if (p_ch == 0 && !ui_has (kUIMessages )&& !msg_scrolled ) { 1709msg_grid_validate (); 1710msg_scroll_up (false, true); 1711msg_scrolled ++ ; 1712cmdline_row = Rows - 1 ; 1713 } 1714 1715if (!msg_scroll && full_screen ) {// overwrite last message 1716msg_row = cmdline_row ; 1717msg_col = 0 ; 1718 }else if ((msg_didout || p_ch == 0 )&& !ui_has (kUIMessages )) {// start message on next line 1719if (p_ch == 0 && !msg_didout && msg_use_printf ()) { 1720msg_puts_display ("\n" ,1 ,0 , false); 1721 }else { 1722msg_putchar ('\n' ); 1723 } 1724did_return = true; 1725cmdline_row = msg_row ; 1726 } 1727if (!msg_didany || lines_left < 0 ) { 1728msg_starthere (); 1729 } 1730if (msg_silent == 0 ) { 1731msg_didout = false;// no output on current line yet 1732 } 1733 1734if (ui_has (kUIMessages )) { 1735msg_ext_ui_flush (); 1736 } 1737 1738// When redirecting, may need to start a new line. 1739if (!did_return ) { 1740redir_write ("\n" ,1 ); 1741 } 1742} 1743 1744/// Note that the current msg position is where messages start. 1745void msg_starthere (void ) 1746{ 1747lines_left = cmdline_row ; 1748msg_didany = false; 1749} 1750 1751void msg_putchar (int c ) 1752{ 1753msg_putchar_hl (c ,0 ); 1754} 1755 1756void msg_putchar_hl (int c ,int hl_id ) 1757{ 1758char buf [MB_MAXCHAR + 1 ]; 1759 1760if (IS_SPECIAL (c )) { 1761buf [0 ]= (char )K_SPECIAL ; 1762buf [1 ]= (char )K_SECOND (c ); 1763buf [2 ]= (char )K_THIRD (c ); 1764buf [3 ]= NUL ; 1765 }else { 1766buf [utf_char2bytes (c ,buf )]= NUL ; 1767 } 1768msg_puts_hl (buf ,hl_id , false); 1769} 1770 1771void msg_outnum (int n ) 1772{ 1773char buf [20 ]; 1774 1775snprintf (buf ,sizeof (buf ),"%d" ,n ); 1776msg_puts (buf ); 1777} 1778 1779void msg_home_replace (const char * fname ) 1780{ 1781msg_home_replace_hl (fname ,0 ); 1782} 1783 1784static void msg_home_replace_hl (const char * fname ,int hl_id ) 1785{ 1786char * name = home_replace_save (NULL ,fname ); 1787msg_outtrans (name ,hl_id , false); 1788xfree (name ); 1789} 1790 1791/// Output "len" characters in "str" (including NULs) with translation 1792/// if "len" is -1, output up to a NUL character. Use highlight "hl_id". 1793/// 1794/// @return the number of characters it takes on the screen. 1795int msg_outtrans (const char * str ,int hl_id ,bool hist ) 1796{ 1797return msg_outtrans_len (str , (int )strlen (str ),hl_id ,hist ); 1798} 1799 1800/// Output one character at "p". 1801/// Handles multi-byte characters. 1802/// 1803/// @return pointer to the next character. 1804const char * msg_outtrans_one (const char * p ,int hl_id ,bool hist ) 1805{ 1806int l ; 1807 1808if ((l = utfc_ptr2len (p ))> 1 ) { 1809msg_outtrans_len (p ,l ,hl_id ,hist ); 1810return p + l ; 1811 } 1812msg_puts_hl (transchar_byte_buf (NULL , (uint8_t )(* p )),hl_id ,hist ); 1813return p + 1 ; 1814} 1815 1816int msg_outtrans_len (const char * msgstr ,int len ,int hl_id ,bool hist ) 1817{ 1818int retval = 0 ; 1819const char * str = msgstr ; 1820const char * plain_start = msgstr ; 1821char * s ; 1822int c ; 1823int save_got_int = got_int ; 1824 1825// Only quit when got_int was set in here. 1826got_int = false; 1827 1828if (hist ) { 1829msg_hist_add (str ,len ,hl_id ); 1830 } 1831 1832// When drawing over the command line no need to clear it later or remove 1833// the mode message. 1834if (msg_silent == 0 && len > 0 && msg_row >=cmdline_row && msg_col == 0 ) { 1835clear_cmdline = false; 1836mode_displayed = false; 1837 } 1838 1839// Go over the string. Special characters are translated and printed. 1840// Normal characters are printed several at a time. 1841while (-- len >=0 && !got_int ) { 1842// Don't include composing chars after the end. 1843int mb_l = utfc_ptr2len_len (str ,len + 1 ); 1844if (mb_l > 1 ) { 1845c = utf_ptr2char (str ); 1846if (vim_isprintc (c )) { 1847// Printable multi-byte char: count the cells. 1848retval += utf_ptr2cells (str ); 1849 }else { 1850// Unprintable multi-byte char: print the printable chars so 1851// far and the translation of the unprintable char. 1852if (str > plain_start ) { 1853msg_puts_len (plain_start ,str - plain_start ,hl_id ,hist ); 1854 } 1855plain_start = str + mb_l ; 1856msg_puts_hl (transchar_buf (NULL ,c ),hl_id == 0 ?HLF_8 :hl_id , false); 1857retval += char2cells (c ); 1858 } 1859len -= mb_l - 1 ; 1860str += mb_l ; 1861 }else { 1862s = transchar_byte_buf (NULL , (uint8_t )(* str )); 1863if (s [1 ]!= NUL ) { 1864// Unprintable char: print the printable chars so far and the 1865// translation of the unprintable char. 1866if (str > plain_start ) { 1867msg_puts_len (plain_start ,str - plain_start ,hl_id ,hist ); 1868 } 1869plain_start = str + 1 ; 1870msg_puts_hl (s ,hl_id == 0 ?HLF_8 :hl_id , false); 1871retval += (int )strlen (s ); 1872 }else { 1873retval ++ ; 1874 } 1875str ++ ; 1876 } 1877 } 1878 1879if ((str > plain_start || plain_start == msgstr )&& !got_int ) { 1880// Print the printable chars at the end (or emit empty string). 1881msg_puts_len (plain_start ,str - plain_start ,hl_id ,hist ); 1882 } 1883 1884got_int |=save_got_int ; 1885 1886return retval ; 1887} 1888 1889void msg_make (const char * arg ) 1890{ 1891int i ; 1892static const char * str = "eeffoc" ; 1893static const char * rs = "Plon#dqg#vxjduB" ; 1894 1895arg = skipwhite (arg ); 1896for (i = 5 ;* arg && i >=0 ;i -- ) { 1897if (* arg ++ != str [i ]) { 1898break ; 1899 } 1900 } 1901if (i < 0 ) { 1902msg_putchar ('\n' ); 1903for (i = 0 ;rs [i ];i ++ ) { 1904msg_putchar (rs [i ]- 3 ); 1905 } 1906 } 1907} 1908 1909/// Output the string 'str' up to a NUL character. 1910/// Return the number of characters it takes on the screen. 1911/// 1912/// If K_SPECIAL is encountered, then it is taken in conjunction with the 1913/// following character and shown as <F1>, <S-Up> etc. Any other character 1914/// which is not printable shown in <> form. 1915/// If 'from' is true (lhs of a mapping), a space is shown as <Space>. 1916/// If a character is displayed in one of these special ways, is also 1917/// highlighted (its highlight name is '8' in the p_hl variable). 1918/// Otherwise characters are not highlighted. 1919/// This function is used to show mappings, where we want to see how to type 1920/// the character/string -- webb 1921/// 1922/// @param from true for LHS of a mapping 1923/// @param maxlen screen columns, 0 for unlimited 1924int msg_outtrans_special (const char * strstart ,bool from ,int maxlen ) 1925{ 1926if (strstart == NULL ) { 1927return 0 ;// Do nothing. 1928 } 1929const char * str = strstart ; 1930int retval = 0 ; 1931int hl_id = HLF_8 ; 1932 1933while (* str != NUL ) { 1934const char * text ; 1935// Leading and trailing spaces need to be displayed in <> form. 1936if ((str == strstart || str [1 ]== NUL )&& * str == ' ' ) { 1937text = "<Space>" ; 1938str ++ ; 1939 }else { 1940text = str2special (& str ,from , false,NULL ); 1941 } 1942if (text [0 ]!= NUL && text [1 ]== NUL ) { 1943// single-byte character or illegal byte 1944text = transchar_byte_buf (NULL , (uint8_t )text [0 ]); 1945 } 1946const int len = vim_strsize (text ); 1947if (maxlen > 0 && retval + len >=maxlen ) { 1948break ; 1949 } 1950// Highlight special keys 1951msg_puts_hl (text , (len > 1 && utfc_ptr2len (text ) <=1 ?hl_id :0 ), false); 1952retval += len ; 1953 } 1954return retval ; 1955} 1956 1957/// Convert string, replacing key codes with printables 1958/// 1959/// Used for lhs or rhs of mappings. 1960/// 1961/// @param[in] str String to convert. 1962/// @param[in] replace_spaces Convert spaces into `<Space>`, normally used for 1963/// lhs of mapping and keytrans(), but not rhs. 1964/// @param[in] replace_others kTrue/kNone: Convert `<` into `<lt>`. 1965/// kTrue: Convert `|` into `<Bar>`, `\` into `<Bslash>`. 1966/// 1967/// @return [allocated] Converted string. 1968char * str2special_save (const char * const str ,const bool replace_spaces , 1969const TriState replace_others ) 1970FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_MALLOC 1971FUNC_ATTR_NONNULL_RET 1972{ 1973garray_T ga ; 1974ga_init (& ga ,1 ,40 ); 1975 1976const char * p = str ; 1977while (* p != NUL ) { 1978ga_concat (& ga ,str2special (& p ,replace_spaces ,replace_others ,NULL )); 1979 } 1980ga_append (& ga ,NUL ); 1981return (char * )ga .ga_data ; 1982} 1983 1984/// Convert string, replacing key codes with printables 1985/// 1986/// Used for lhs or rhs of mappings. 1987/// 1988/// @param[in] str String to convert. 1989/// @param[in] replace_spaces Convert spaces into `<Space>`, normally used for 1990/// lhs of mapping and keytrans(), but not rhs. 1991/// @param[in] replace_others kTrue/kNone: Convert `<` into `<lt>`. 1992/// kTrue: Convert `|` into `<Bar>`, `\` into `<Bslash>`. 1993/// 1994/// @return [allocated] Converted string. 1995char * str2special_arena (const char * const str ,const bool replace_spaces , 1996const TriState replace_others ,Arena * const arena ) 1997FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_MALLOC 1998FUNC_ATTR_NONNULL_RET 1999{ 2000const char * p = str ; 2001size_t len = 0 ; 2002while (* p ) { 2003len += strlen (str2special (& p ,replace_spaces ,replace_others ,NULL )); 2004 } 2005 2006char * buf = arena_alloc (arena ,len + 1 , false); 2007size_t pos = 0 ; 2008p = str ; 2009while (* p ) { 2010const char * s = str2special (& p ,replace_spaces ,replace_others ,NULL ); 2011size_t s_len = strlen (s ); 2012memcpy (buf + pos ,s ,s_len ); 2013pos += s_len ; 2014 } 2015buf [pos ]= NUL ; 2016return buf ; 2017} 2018 2019/// Convert character, replacing key with printable representation. 2020/// 2021/// @param[in,out] sp String to convert. Is advanced to the next key code. 2022/// @param[in] replace_spaces Convert spaces into `<Space>`, normally used for 2023/// lhs of mapping and keytrans(), but not rhs. 2024/// @param[in] replace_others kTrue/kNone: Convert `<` into `<lt>`. 2025/// kTrue: Convert `|` into `<Bar>`, `\` into `<Bslash>`. 2026/// @param[out] data If non-NULL, gets structured info about the key chord. 2027/// 2028/// @return Converted key code, in a static buffer. Buffer is always one and the 2029/// same, so save converted string somewhere before running str2special 2030/// for the second time. 2031/// On illegal byte return a string with only that byte. 2032const char * str2special (const char ** const sp ,const bool replace_spaces , 2033const TriState replace_others ,struct keychord * data ) 2034FUNC_ATTR_NONNULL_ARG (1 )FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_RET 2035{ 2036static char buf [7 ]; 2037 2038 { 2039// Try to un-escape a multi-byte character. Return the un-escaped 2040// string if it is a multi-byte character. 2041const char * const p = mb_unescape (sp ); 2042if (p != NULL ) { 2043if (data ) { 2044data -> mods = 0 ; 2045data -> key = (String ){ (char * )p ,strlen (p ) }; 2046data -> key_alt = (String ){NULL ,0 }; 2047 } 2048 2049return p ; 2050 } 2051 } 2052 2053const char * str = * sp ; 2054int c = (uint8_t )(* str ); 2055int modifiers = 0 ; 2056bool special = false; 2057if (c == K_SPECIAL && str [1 ]!= NUL && str [2 ]!= NUL ) { 2058if ((uint8_t )str [1 ]== KS_MODIFIER ) { 2059modifiers = (uint8_t )str [2 ]; 2060str += 3 ; 2061c = (uint8_t )(* str ); 2062 } 2063if (c == K_SPECIAL && str [1 ]!= NUL && str [2 ]!= NUL ) { 2064c = TO_SPECIAL ((uint8_t )str [1 ], (uint8_t )str [2 ]); 2065str += 2 ; 2066 } 2067if (IS_SPECIAL (c )|| modifiers ) {// Special key. 2068special = true; 2069 } 2070 } 2071 2072if (!IS_SPECIAL (c )&& MB_BYTE2LEN (c )> 1 ) { 2073* sp = str ; 2074// Try to un-escape a multi-byte character after modifiers. 2075const char * p = mb_unescape (sp ); 2076if (p != NULL ) { 2077// Since 'special' is true the multi-byte character 'c' will be 2078// processed by get_special_key_name(). 2079c = utf_ptr2char (p ); 2080 }else { 2081// illegal byte 2082* sp = str + 1 ; 2083 } 2084 }else { 2085// single-byte character, NUL or illegal byte 2086* sp = str + (* str == NUL ?0 :1 ); 2087 } 2088 2089// Make special keys and C0 control characters in <> form, also <M-Space>. 2090if (special 2091|| c < ' ' 2092|| (replace_spaces && c == ' ' ) 2093|| (replace_others != kFalse && c == '<' ) 2094|| (replace_others == kTrue && (c == '|' || c == '\\' ))) { 2095return get_special_key (c ,modifiers ,data ); 2096 } 2097 2098if (data ) { 2099data -> mods = 0 ; 2100if ('A' <=c && c <='Z' ) { 2101data -> key_mem = (char )c + 32 ; 2102data -> key = (String ){& data -> key_mem ,1 }; 2103data -> mods |=MOD_MASK_SHIFT ; 2104data -> key_alt = (String ){buf ,1 }; 2105 }else { 2106data -> key = (String ){buf ,1 }; 2107data -> key_alt = (String ){NULL ,0 }; 2108 } 2109 } 2110 2111buf [0 ]= (char )c ; 2112buf [1 ]= NUL ; 2113return buf ; 2114} 2115 2116/// Convert string, replacing key codes with printables 2117/// 2118/// @param[in] str String to convert. 2119/// @param[out] buf Buffer to save results to. 2120/// @param[in] len Buffer length. 2121void str2specialbuf (const char * sp ,char * buf ,size_t len ) 2122FUNC_ATTR_NONNULL_ALL 2123{ 2124while (* sp ) { 2125const char * s = str2special (& sp , false, false,NULL ); 2126const size_t s_len = strlen (s ); 2127if (len <=s_len ) { 2128break ; 2129 } 2130memcpy (buf ,s ,s_len ); 2131buf += s_len ; 2132len -= s_len ; 2133 } 2134* buf = NUL ; 2135} 2136 2137/// print line for :print or :list command 2138void msg_prt_line (const char * s ,bool list ) 2139{ 2140schar_T sc ; 2141int col = 0 ; 2142int n_extra = 0 ; 2143schar_T sc_extra = 0 ; 2144schar_T sc_final = 0 ; 2145const char * p_extra = NULL ;// init to make SASC shut up. ASCII only! 2146int n ; 2147int hl_id = 0 ; 2148const char * lead = NULL ; 2149bool in_multispace = false; 2150int multispace_pos = 0 ; 2151const char * trail = NULL ; 2152int l ; 2153 2154if (curwin -> w_p_list ) { 2155list = true; 2156 } 2157 2158if (list ) { 2159// find start of trailing whitespace 2160if (curwin -> w_p_lcs_chars .trail ) { 2161trail = s + strlen (s ); 2162while (trail > s && ascii_iswhite (trail [-1 ])) { 2163trail -- ; 2164 } 2165 } 2166// find end of leading whitespace 2167if (curwin -> w_p_lcs_chars .lead 2168|| curwin -> w_p_lcs_chars .leadmultispace != NULL 2169|| curwin -> w_p_lcs_chars .leadtab1 != NUL ) { 2170lead = s ; 2171while (ascii_iswhite (lead [0 ])) { 2172lead ++ ; 2173 } 2174// in a line full of spaces all of them are treated as trailing 2175if (* lead == NUL ) { 2176lead = NULL ; 2177 } 2178 } 2179 } 2180 2181// output a space for an empty line, otherwise the line will be overwritten 2182if (* s == NUL && !(list && curwin -> w_p_lcs_chars .eol != NUL )) { 2183msg_putchar (' ' ); 2184 } 2185 2186while (!got_int ) { 2187if (n_extra > 0 ) { 2188n_extra -- ; 2189if (n_extra == 0 && sc_final ) { 2190sc = sc_final ; 2191 }else if (sc_extra ) { 2192sc = sc_extra ; 2193 }else { 2194assert (p_extra != NULL ); 2195sc = schar_from_ascii ((unsigned char )(* p_extra ++ )); 2196 } 2197 }else if ((l = utfc_ptr2len (s ))> 1 ) { 2198col += utf_ptr2cells (s ); 2199char buf [MB_MAXBYTES + 1 ]; 2200if (l >=MB_MAXBYTES ) { 2201xstrlcpy (buf ,"?" ,sizeof (buf )); 2202 }else if (curwin -> w_p_lcs_chars .nbsp != NUL && list 2203&& (utf_ptr2char (s )== 160 || utf_ptr2char (s )== 0x202f )) { 2204schar_get (buf ,curwin -> w_p_lcs_chars .nbsp ); 2205 }else { 2206memmove (buf ,s , (size_t )l ); 2207buf [l ]= NUL ; 2208 } 2209msg_puts (buf ); 2210s += l ; 2211continue ; 2212 }else { 2213hl_id = 0 ; 2214int c = (uint8_t )(* s ++ ); 2215if (c >=0x80 ) {// Illegal byte 2216col += utf_char2cells (c ); 2217msg_putchar (c ); 2218continue ; 2219 } 2220sc_extra = NUL ; 2221sc_final = NUL ; 2222if (list ) { 2223in_multispace = c == ' ' && (* s == ' ' 2224|| (col > 0 && s [-2 ]== ' ' )); 2225if (!in_multispace ) { 2226multispace_pos = 0 ; 2227 } 2228 } 2229if (c == TAB && (!list || curwin -> w_p_lcs_chars .tab1 )) { 2230// tab amount depends on current column 2231n_extra = tabstop_padding (col ,curbuf -> b_p_ts , 2232curbuf -> b_p_vts_array )- 1 ; 2233if (!list ) { 2234sc = schar_from_ascii (' ' ); 2235sc_extra = schar_from_ascii (' ' ); 2236 }else { 2237schar_T lcs_tab1 = curwin -> w_p_lcs_chars .tab1 ; 2238schar_T lcs_tab2 = curwin -> w_p_lcs_chars .tab2 ; 2239schar_T lcs_tab3 = curwin -> w_p_lcs_chars .tab3 ; 2240// check if leadtab is set in 'listchars' 2241if (lead != NULL && s <=lead && curwin -> w_p_lcs_chars .leadtab1 != NUL ) { 2242lcs_tab1 = curwin -> w_p_lcs_chars .leadtab1 ; 2243lcs_tab2 = curwin -> w_p_lcs_chars .leadtab2 ; 2244lcs_tab3 = curwin -> w_p_lcs_chars .leadtab3 ; 2245 } 2246sc = (n_extra == 0 && lcs_tab3 ) ?lcs_tab3 :lcs_tab1 ; 2247sc_extra = lcs_tab2 ; 2248sc_final = lcs_tab3 ; 2249hl_id = HLF_0 ; 2250 } 2251 }else if (c == NUL && list && curwin -> w_p_lcs_chars .eol != NUL ) { 2252p_extra = "" ; 2253n_extra = 1 ; 2254sc = curwin -> w_p_lcs_chars .eol ; 2255hl_id = HLF_AT ; 2256s -- ; 2257 }else if (c != NUL && (n = ascii2cells (c ))> 1 ) { 2258n_extra = n - 1 ; 2259p_extra = transchar_byte_buf (NULL ,c ); 2260sc = schar_from_ascii (* p_extra ++ ); 2261// Use special coloring to be able to distinguish <hex> from 2262// the same in plain text. 2263hl_id = HLF_0 ; 2264 }else if (c == ' ' ) { 2265if (lead != NULL && s <=lead && in_multispace 2266&& curwin -> w_p_lcs_chars .leadmultispace != NULL ) { 2267sc = curwin -> w_p_lcs_chars .leadmultispace [multispace_pos ++ ]; 2268if (curwin -> w_p_lcs_chars .leadmultispace [multispace_pos ]== NUL ) { 2269multispace_pos = 0 ; 2270 } 2271hl_id = HLF_0 ; 2272 }else if (lead != NULL && s <=lead && curwin -> w_p_lcs_chars .lead != NUL ) { 2273sc = curwin -> w_p_lcs_chars .lead ; 2274hl_id = HLF_0 ; 2275 }else if (trail != NULL && s > trail ) { 2276sc = curwin -> w_p_lcs_chars .trail ; 2277hl_id = HLF_0 ; 2278 }else if (in_multispace 2279&& curwin -> w_p_lcs_chars .multispace != NULL ) { 2280sc = curwin -> w_p_lcs_chars .multispace [multispace_pos ++ ]; 2281if (curwin -> w_p_lcs_chars .multispace [multispace_pos ]== NUL ) { 2282multispace_pos = 0 ; 2283 } 2284hl_id = HLF_0 ; 2285 }else if (list && curwin -> w_p_lcs_chars .space != NUL ) { 2286sc = curwin -> w_p_lcs_chars .space ; 2287hl_id = HLF_0 ; 2288 }else { 2289sc = schar_from_ascii (' ' );// SPACE! 2290 } 2291 }else { 2292sc = schar_from_ascii (c ); 2293 } 2294 } 2295 2296if (sc == NUL ) { 2297break ; 2298 } 2299 2300// TODO(bfredl): this is such baloney. need msg_put_schar 2301char buf [MAX_SCHAR_SIZE ]; 2302schar_get (buf ,sc ); 2303msg_puts_hl (buf ,hl_id , false); 2304col ++ ; 2305 } 2306msg_clr_eos (); 2307} 2308 2309/// Output a string to the screen at position msg_row, msg_col. 2310/// Update msg_row and msg_col for the next message. 2311void msg_puts (const char * s ) 2312{ 2313msg_puts_hl (s ,0 , false); 2314} 2315 2316void msg_puts_title (const char * s ) 2317{ 2318s += (ui_has (kUIMessages )&& * s == '\n' ); 2319msg_puts_hl (s ,HLF_T , false); 2320} 2321 2322/// Show a message in such a way that it always fits in the line. Cut out a 2323/// part in the middle and replace it with "..." when necessary. 2324/// Does not handle multi-byte characters! 2325void msg_outtrans_long (const char * longstr ,int hl_id ) 2326{ 2327int len = (int )strlen (longstr ); 2328int slen = len ; 2329int room = Columns - msg_col ; 2330if (!ui_has (kUIMessages )&& len > room && room >=20 ) { 2331slen = (room - 3 ) /2 ; 2332msg_outtrans_len (longstr ,slen ,hl_id , false); 2333msg_puts_hl ("..." ,HLF_8 , false); 2334 } 2335msg_outtrans_len (longstr + len - slen ,slen ,hl_id , false); 2336} 2337 2338/// Basic function for writing a message with highlight id. 2339void msg_puts_hl (const char * const s ,const int hl_id ,const bool hist ) 2340{ 2341msg_puts_len (s ,-1 ,hl_id ,hist ); 2342} 2343 2344/// Write a message with highlight id. 2345/// 2346/// @param[in] str NUL-terminated message string. 2347/// @param[in] len Length of the string or -1. 2348/// @param[in] hl_id Highlight id. 2349void msg_puts_len (const char * const str ,const ptrdiff_t len ,int hl_id ,bool hist ) 2350FUNC_ATTR_NONNULL_ALL 2351{ 2352assert (len < 0 || memchr (str ,0 , (size_t )len )== NULL ); 2353// If redirection is on, also write to the redirection file. 2354redir_write (str ,len ); 2355 2356// Don't print anything when using ":silent cmd" or empty message. 2357if (msg_silent != 0 || * str == NUL ) { 2358if (* str == NUL && ui_has (kUIMessages )) { 2359msg_ext_no_fast (); 2360ui_call_msg_show (cstr_as_string ("empty" ), (Array )ARRAY_DICT_INIT , false, false, false, 2361INTEGER_OBJ (-1 ), (String )STRING_INIT ); 2362cmdline_was_last_drawn = false; 2363 } 2364return ; 2365 } 2366 2367if (hist ) { 2368msg_hist_add (str , (int )len ,hl_id ); 2369 } 2370 2371// When writing something to the screen after it has scrolled, requires a 2372// wait-return prompt later. Needed when scrolling, resetting 2373// need_wait_return after some prompt, and then outputting something 2374// without scrolling 2375// Not needed when only using CR to move the cursor. 2376bool overflow = !ui_has (kUIMessages )&& msg_scrolled > (p_ch == 0 ?1 :0 ); 2377 2378if (overflow && !msg_scrolled_ign && strcmp (str ,"\r" )!= 0 ) { 2379need_wait_return = true; 2380 } 2381msg_didany = true;// remember that something was outputted 2382 2383// If there is no valid screen, use fprintf so we can see error messages. 2384// If termcap is not active, we may be writing in an alternate console 2385// window, cursor positioning may not work correctly (window size may be 2386// different, e.g. for Win32 console) or we just don't know where the 2387// cursor is. 2388if (msg_use_printf ()) { 2389int saved_msg_col = msg_col ; 2390msg_puts_printf (str ,len ); 2391if (headless_mode ) { 2392msg_col = saved_msg_col ; 2393 } 2394 } 2395if (!msg_use_printf ()|| (headless_mode && default_grid .chars )) { 2396msg_puts_display (str , (int )len ,hl_id , false); 2397 } 2398 2399need_fileinfo = false; 2400} 2401 2402static void msg_ext_emit_chunk (void ) 2403{ 2404if (msg_ext_chunks == NULL ) { 2405msg_ext_init_chunks (); 2406 } 2407// Color was changed or a message flushed, end current chunk. 2408if (msg_ext_last_attr == -1 ) { 2409return ;// no chunk 2410 } 2411Array chunk = ARRAY_DICT_INIT ; 2412ADD (chunk ,INTEGER_OBJ (msg_ext_last_attr )); 2413msg_ext_last_attr = -1 ; 2414String text = ga_take_string (& msg_ext_last_chunk ); 2415ADD (chunk ,STRING_OBJ (text )); 2416ADD (chunk ,INTEGER_OBJ (msg_ext_last_hl_id )); 2417ADD (* msg_ext_chunks ,ARRAY_OBJ (chunk )); 2418} 2419 2420/// The display part of msg_puts_len(). 2421/// May be called recursively to display scroll-back text. 2422static void msg_puts_display (const char * str ,int maxlen ,int hl_id ,int recurse ) 2423{ 2424const char * s = str ; 2425const char * sb_str = str ; 2426int sb_col = msg_col ; 2427int attr = hl_id ?syn_id2attr (hl_id ) :0 ; 2428 2429did_wait_return = false; 2430 2431if (ui_has (kUIMessages )) { 2432if (attr != msg_ext_last_attr ) { 2433msg_ext_emit_chunk (); 2434msg_ext_last_attr = attr ; 2435msg_ext_last_hl_id = hl_id ; 2436 } 2437// Concat pieces with the same highlight 2438size_t len = maxlen < 0 ?strlen (str ) :strnlen (str , (size_t )maxlen ); 2439ga_concat_len (& msg_ext_last_chunk ,str ,len ); 2440 2441// Find last newline in the message and calculate the current message column 2442const char * lastline = xmemrchr (str ,'\n' ,len ); 2443maxlen -= (int )(lastline ? (lastline - str ) :0 ); 2444const char * p = lastline ?lastline + 1 :str ; 2445int col = (int )(maxlen < 0 ?mb_string2cells (p ) :mb_string2cells_len (p , (size_t )maxlen )); 2446msg_col = (lastline ?0 :msg_col )+ col ; 2447 2448return ; 2449 } 2450 2451int print_attr = hl_combine_attr (HL_ATTR (HLF_MSG ),attr ); 2452msg_grid_validate (); 2453 2454cmdline_was_last_drawn = redrawing_cmdline ; 2455 2456int msg_row_pending = -1 ; 2457 2458while (true) { 2459if (msg_col >=Columns ) { 2460if (p_more && !recurse ) { 2461// Store text for scrolling back. 2462store_sb_text (& sb_str ,s ,hl_id ,& sb_col , true); 2463 } 2464if (msg_no_more && lines_left == 0 ) { 2465break ; 2466 } 2467 2468msg_col = 0 ; 2469msg_row ++ ; 2470msg_didout = false; 2471 } 2472 2473if (msg_row >=Rows ) { 2474msg_row = Rows - 1 ; 2475 2476// When no more prompt and no more room, truncate here 2477if (msg_no_more && lines_left == 0 ) { 2478break ; 2479 } 2480 2481if (!recurse ) { 2482if (msg_row_pending >=0 ) { 2483msg_line_flush (); 2484msg_row_pending = -1 ; 2485 } 2486 2487// Scroll the screen up one line. 2488msg_scroll_up (true, false); 2489 2490inc_msg_scrolled (); 2491need_wait_return = true;// may need wait_return() in main() 2492redraw_cmdline = true; 2493if (cmdline_row > 0 ) { 2494cmdline_row -- ; 2495 } 2496 2497// If screen is completely filled and 'more' is set then wait 2498// for a character. 2499if (lines_left > 0 ) { 2500lines_left -- ; 2501 } 2502 2503if (p_more && lines_left == 0 && State != MODE_HITRETURN 2504&& !msg_no_more ) { 2505if (do_more_prompt (NUL )) { 2506s = confirm_buttons ; 2507 } 2508if (quit_more ) { 2509return ; 2510 } 2511 } 2512 } 2513 } 2514 2515if (!((maxlen < 0 || (int )(s - str )< maxlen )&& * s != NUL )) { 2516break ; 2517 } 2518 2519if (msg_row != msg_row_pending && ((uint8_t )(* s ) >=0x20 || * s == TAB )) { 2520// TODO(bfredl): this logic is messier that it has to be. What 2521// messages really want is its own private linebuf_char buffer. 2522if (msg_row_pending >=0 ) { 2523msg_line_flush (); 2524 } 2525grid_line_start (& msg_grid_adj ,msg_row ); 2526msg_row_pending = msg_row ; 2527 } 2528 2529if ((uint8_t )(* s ) >=0x20 ) {// printable char 2530int cw = utf_ptr2cells (s ); 2531// avoid including composing chars after the end 2532int l = (maxlen >=0 ) ?utfc_ptr2len_len (s , (int )((str + maxlen )- s )) :utfc_ptr2len (s ); 2533 2534if (cw > 1 && (msg_col == Columns - 1 )) { 2535// Doesn't fit, print a highlighted '>' to fill it up. 2536grid_line_puts (msg_col ,">" ,1 ,HL_ATTR (HLF_AT )); 2537cw = 1 ; 2538 }else { 2539grid_line_puts (msg_col ,s ,l ,print_attr ); 2540s += l ; 2541 } 2542msg_didout = true;// remember that line is not empty 2543msg_col += cw ; 2544 }else { 2545char c = * s ++ ; 2546if (c == '\n' ) {// go to next line 2547msg_didout = false;// remember that line is empty 2548msg_col = 0 ; 2549msg_row ++ ; 2550if (p_more && !recurse ) { 2551// Store text for scrolling back. 2552store_sb_text (& sb_str ,s ,hl_id ,& sb_col , true); 2553 } 2554 }else if (c == '\r' ) {// go to column 0 2555msg_col = 0 ; 2556 }else if (c == '\b' ) {// go to previous char 2557if (msg_col ) { 2558msg_col -- ; 2559 } 2560 }else if (c == TAB ) {// translate Tab into spaces 2561do { 2562grid_line_puts (msg_col ," " ,1 ,print_attr ); 2563msg_col += 1 ; 2564 2565if (msg_col == Columns ) { 2566break ; 2567 } 2568 }while (msg_col & 7 ); 2569 }else if (c == BELL ) {// beep (from ":sh") 2570vim_beep (kOptBoFlagShell ); 2571 } 2572 } 2573 } 2574 2575if (msg_row_pending >=0 ) { 2576msg_line_flush (); 2577 } 2578msg_cursor_goto (msg_row ,msg_col ); 2579 2580if (p_more && !recurse ) { 2581store_sb_text (& sb_str ,s ,hl_id ,& sb_col , false); 2582 } 2583 2584msg_check (); 2585} 2586 2587void msg_line_flush (void ) 2588{ 2589if (cmdmsg_rl ) { 2590grid_line_mirror (msg_grid .cols ); 2591 } 2592grid_line_flush_if_valid_row (); 2593} 2594 2595void msg_cursor_goto (int row ,int col ) 2596{ 2597if (cmdmsg_rl ) { 2598col = Columns - 1 - col ; 2599 } 2600ScreenGrid * grid = grid_adjust (& msg_grid_adj ,& row ,& col ); 2601ui_grid_cursor_goto (grid -> handle ,row ,col ); 2602} 2603 2604/// @return true when ":filter pattern" was used and "msg" does not match 2605/// "pattern". 2606bool message_filtered (const char * msg ) 2607{ 2608if (cmdmod .cmod_filter_regmatch .regprog == NULL ) { 2609return false; 2610 } 2611 2612bool match = vim_regexec (& cmdmod .cmod_filter_regmatch ,msg ,0 ); 2613return cmdmod .cmod_filter_force ?match : !match ; 2614} 2615 2616/// including horizontal separator 2617int msg_scrollsize (void ) 2618{ 2619return msg_scrolled + (int )p_ch + ((p_ch > 0 || msg_scrolled > 1 ) ?1 :0 ); 2620} 2621 2622bool msg_do_throttle (void ) 2623{ 2624return msg_use_grid ()&& !(rdb_flags & kOptRdbFlagNothrottle ); 2625} 2626 2627/// Scroll the screen up one line for displaying the next message line. 2628void msg_scroll_up (bool may_throttle ,bool zerocmd ) 2629{ 2630if (may_throttle && msg_do_throttle ()) { 2631msg_grid .throttled = true; 2632 } 2633msg_did_scroll = true; 2634if (msg_grid_pos > 0 ) { 2635msg_grid_set_pos (msg_grid_pos - 1 , !zerocmd ); 2636 2637// When displaying the first line with cmdheight=0, we need to draw over 2638// the existing last line of the screen. 2639if (zerocmd && msg_grid .chars ) { 2640grid_clear_line (& msg_grid ,msg_grid .line_offset [0 ],msg_grid .cols , false); 2641 } 2642 }else { 2643grid_del_lines (& msg_grid ,0 ,1 ,msg_grid .rows ,0 ,msg_grid .cols ); 2644memmove (msg_grid .dirty_col ,msg_grid .dirty_col + 1 , 2645 (size_t )(msg_grid .rows - 1 )* sizeof (* msg_grid .dirty_col )); 2646msg_grid .dirty_col [msg_grid .rows - 1 ]= 0 ; 2647 } 2648 2649grid_clear (& msg_grid_adj ,Rows - 1 ,Rows ,0 ,Columns ,HL_ATTR (HLF_MSG )); 2650} 2651 2652/// Send throttled message output to UI clients 2653/// 2654/// The way message.c uses the grid_xx family of functions is quite inefficient 2655/// relative to the "gridline" UI protocol used by TUI and modern clients. 2656/// For instance scrolling is done one line at a time. By throttling drawing 2657/// on the message grid, we can coalesce scrolling to a single grid_scroll 2658/// per screen update. 2659/// 2660/// NB: The bookkeeping is quite messy, and rests on a bunch of poorly 2661/// documented assumptions. For instance that the message area always grows 2662/// while being throttled, messages are only being output on the last line 2663/// etc. 2664/// 2665/// Probably message scrollback storage should be reimplemented as a 2666/// file_buffer, and message scrolling in TUI be reimplemented as a modal 2667/// floating window. Then we get throttling "for free" using standard 2668/// redraw_later code paths. 2669void msg_scroll_flush (void ) 2670{ 2671if (msg_grid .throttled ) { 2672msg_grid .throttled = false; 2673int pos_delta = msg_grid_pos_at_flush - msg_grid_pos ; 2674assert (pos_delta >=0 ); 2675int delta = MIN (msg_scrolled - msg_scrolled_at_flush ,msg_grid .rows ); 2676 2677if (pos_delta > 0 ) { 2678ui_ext_msg_set_pos (msg_grid_pos , true); 2679 } 2680 2681int to_scroll = delta - pos_delta - msg_grid_scroll_discount ; 2682assert (to_scroll >=0 ); 2683 2684// TODO(bfredl): msg_grid_pos should be 0 already when starting scrolling 2685// but this sometimes fails in "headless" message printing. 2686if (to_scroll > 0 && msg_grid_pos == 0 ) { 2687ui_call_grid_scroll (msg_grid .handle ,0 ,Rows ,0 ,Columns ,to_scroll ,0 ); 2688 } 2689 2690for (int i = MAX (Rows - MAX (delta ,1 ),0 );i < Rows ;i ++ ) { 2691int row = i - msg_grid_pos ; 2692assert (row >=0 ); 2693ui_line (& msg_grid ,row , false,0 ,msg_grid .dirty_col [row ],msg_grid .cols , 2694HL_ATTR (HLF_MSG ), false); 2695msg_grid .dirty_col [row ]= 0 ; 2696 } 2697 } 2698msg_scrolled_at_flush = msg_scrolled ; 2699msg_grid_scroll_discount = 0 ; 2700msg_grid_pos_at_flush = msg_grid_pos ; 2701} 2702 2703void msg_reset_scroll (void ) 2704{ 2705if (ui_has (kUIMessages )) { 2706return ; 2707 } 2708// TODO(bfredl): some duplicate logic with update_screen(). Later on 2709// we should properly disentangle message clear with full screen redraw. 2710msg_grid .throttled = false; 2711// TODO(bfredl): risk for extra flicker i e with 2712// "nvim -o has_swap also_has_swap" 2713msg_grid_set_pos (Rows - (int )p_ch , false); 2714clear_cmdline = true; 2715if (msg_grid .chars ) { 2716// non-displayed part of msg_grid is considered invalid. 2717for (int i = 0 ;i < MIN (msg_scrollsize (),msg_grid .rows );i ++ ) { 2718grid_clear_line (& msg_grid ,msg_grid .line_offset [i ], 2719msg_grid .cols , false); 2720 } 2721 } 2722msg_scrolled = 0 ; 2723msg_scrolled_at_flush = 0 ; 2724msg_grid_scroll_discount = 0 ; 2725} 2726 2727void msg_ui_refresh (void ) 2728{ 2729if (ui_has (kUIMultigrid )&& msg_grid .chars ) { 2730ui_call_grid_resize (msg_grid .handle ,msg_grid .cols ,msg_grid .rows ); 2731ui_ext_msg_set_pos (msg_grid_pos ,msg_scrolled ); 2732 } 2733} 2734 2735void msg_ui_flush (void ) 2736{ 2737if (ui_has (kUIMultigrid )&& msg_grid .chars && msg_grid .pending_comp_index_update ) { 2738ui_ext_msg_set_pos (msg_grid_pos ,msg_scrolled ); 2739 } 2740} 2741 2742/// Increment "msg_scrolled". 2743static void inc_msg_scrolled (void ) 2744{ 2745if (* get_vim_var_str (VV_SCROLLSTART )== NUL ) { 2746String p = { .data = SOURCING_NAME }; 2747char * tofree = NULL ; 2748 2749// v:scrollstart is empty, set it to the script/function name and line 2750// number 2751if (p .data == NULL ) { 2752p = cstr_as_string (_ ("Unknown" )); 2753 }else { 2754size_t tofreesize = strlen (p .data )+ 40 ; 2755tofree = xmalloc (tofreesize ); 2756p .size = vim_snprintf_safelen (tofree ,tofreesize ,_ ("%s line %" PRId64 ), 2757p .data , (int64_t )SOURCING_LNUM ); 2758p .data = tofree ; 2759 } 2760set_vim_var_string (VV_SCROLLSTART ,p .data , (ptrdiff_t )p .size ); 2761xfree (tofree ); 2762 } 2763msg_scrolled ++ ; 2764set_must_redraw (UPD_VALID ); 2765} 2766 2767static msgchunk_T * last_msgchunk = NULL ;// last displayed text 2768 2769typedef enum { 2770SB_CLEAR_NONE = 0 , 2771SB_CLEAR_ALL , 2772SB_CLEAR_CMDLINE_BUSY , 2773SB_CLEAR_CMDLINE_DONE , 2774}sb_clear_T ; 2775 2776// When to clear text on next msg. 2777static sb_clear_T do_clear_sb_text = SB_CLEAR_NONE ; 2778 2779/// Store part of a printed message for displaying when scrolling back. 2780/// 2781/// @param sb_str start of string 2782/// @param s just after string 2783/// @param finish line ends 2784static void store_sb_text (const char ** sb_str ,const char * s ,int hl_id ,int * sb_col ,int finish ) 2785{ 2786msgchunk_T * mp ; 2787 2788if (do_clear_sb_text == SB_CLEAR_ALL 2789|| do_clear_sb_text == SB_CLEAR_CMDLINE_DONE ) { 2790clear_sb_text (do_clear_sb_text == SB_CLEAR_ALL ); 2791msg_sb_eol ();// prevent messages from overlapping 2792if (do_clear_sb_text == SB_CLEAR_CMDLINE_DONE && s > * sb_str && ** sb_str == '\n' ) { 2793 (* sb_str )++ ; 2794 } 2795do_clear_sb_text = SB_CLEAR_NONE ; 2796 } 2797 2798if (s > * sb_str ) { 2799mp = xmalloc (offsetof(msgchunk_T ,sb_text )+ (size_t )(s - * sb_str )+ 1 ); 2800mp -> sb_eol = (char )finish ; 2801mp -> sb_msg_col = * sb_col ; 2802mp -> sb_hl_id = hl_id ; 2803memcpy (mp -> sb_text ,* sb_str , (size_t )(s - * sb_str )); 2804mp -> sb_text [s - * sb_str ]= NUL ; 2805 2806if (last_msgchunk == NULL ) { 2807last_msgchunk = mp ; 2808mp -> sb_prev = NULL ; 2809 }else { 2810mp -> sb_prev = last_msgchunk ; 2811last_msgchunk -> sb_next = mp ; 2812last_msgchunk = mp ; 2813 } 2814mp -> sb_next = NULL ; 2815 }else if (finish && last_msgchunk != NULL ) { 2816last_msgchunk -> sb_eol = true; 2817 } 2818 2819* sb_str = s ; 2820* sb_col = 0 ; 2821} 2822 2823/// Finished showing messages, clear the scroll-back text on the next message. 2824void may_clear_sb_text (void ) 2825{ 2826msg_ext_ui_flush ();// ensure messages until now are emitted 2827do_clear_sb_text = SB_CLEAR_ALL ; 2828do_clear_hist_temp = true; 2829} 2830 2831/// Starting to edit the command line: do not clear messages now. 2832void sb_text_start_cmdline (void ) 2833{ 2834if (do_clear_sb_text == SB_CLEAR_CMDLINE_BUSY ) { 2835// Invoking command line recursively: the previous-level command line 2836// doesn't need to be remembered as it will be redrawn when returning 2837// to that level. 2838sb_text_restart_cmdline (); 2839 }else { 2840msg_sb_eol (); 2841do_clear_sb_text = SB_CLEAR_CMDLINE_BUSY ; 2842 } 2843} 2844 2845/// Redrawing the command line: clear the last unfinished line. 2846void sb_text_restart_cmdline (void ) 2847{ 2848// Needed when returning from nested command line. 2849do_clear_sb_text = SB_CLEAR_CMDLINE_BUSY ; 2850 2851if (last_msgchunk == NULL || last_msgchunk -> sb_eol ) { 2852// No unfinished line: don't clear anything. 2853return ; 2854 } 2855 2856msgchunk_T * tofree = msg_sb_start (last_msgchunk ); 2857last_msgchunk = tofree -> sb_prev ; 2858if (last_msgchunk != NULL ) { 2859last_msgchunk -> sb_next = NULL ; 2860 } 2861while (tofree != NULL ) { 2862msgchunk_T * tofree_next = tofree -> sb_next ; 2863xfree (tofree ); 2864tofree = tofree_next ; 2865 } 2866} 2867 2868/// Ending to edit the command line: clear old lines but the last one later. 2869void sb_text_end_cmdline (void ) 2870{ 2871do_clear_sb_text = SB_CLEAR_CMDLINE_DONE ; 2872} 2873 2874/// Clear any text remembered for scrolling back. 2875/// When "all" is false keep the last line. 2876/// Called when redrawing the screen. 2877void clear_sb_text (bool all ) 2878{ 2879msgchunk_T * mp ; 2880msgchunk_T ** lastp ; 2881 2882if (all ) { 2883lastp = & last_msgchunk ; 2884 }else { 2885if (last_msgchunk == NULL ) { 2886return ; 2887 } 2888lastp = & msg_sb_start (last_msgchunk )-> sb_prev ; 2889 } 2890 2891while (* lastp != NULL ) { 2892mp = (* lastp )-> sb_prev ; 2893xfree (* lastp ); 2894* lastp = mp ; 2895 } 2896} 2897 2898/// "g<" command. 2899void show_sb_text (void ) 2900{ 2901if (ui_has (kUIMessages )) { 2902exarg_T ea = { .arg = "" , .skip = true }; 2903ex_messages (& ea ); 2904return ; 2905 } 2906// Only show something if there is more than one line, otherwise it looks 2907// weird, typing a command without output results in one line. 2908msgchunk_T * mp = msg_sb_start (last_msgchunk ); 2909if (mp == NULL || mp -> sb_prev == NULL ) { 2910vim_beep (kOptBoFlagMess ); 2911 }else { 2912do_more_prompt ('G' ); 2913wait_return (false); 2914 } 2915} 2916 2917/// Move to the start of screen line in already displayed text. 2918static msgchunk_T * msg_sb_start (msgchunk_T * mps ) 2919{ 2920msgchunk_T * mp = mps ; 2921 2922while (mp != NULL && mp -> sb_prev != NULL && !mp -> sb_prev -> sb_eol ) { 2923mp = mp -> sb_prev ; 2924 } 2925return mp ; 2926} 2927 2928/// Mark the last message chunk as finishing the line. 2929void msg_sb_eol (void ) 2930{ 2931if (last_msgchunk != NULL ) { 2932last_msgchunk -> sb_eol = true; 2933 } 2934} 2935 2936/// Display a screen line from previously displayed text at row "row". 2937/// 2938/// @return a pointer to the text for the next line (can be NULL). 2939static msgchunk_T * disp_sb_line (int row ,msgchunk_T * smp ) 2940{ 2941msgchunk_T * mp = smp ; 2942 2943while (true) { 2944msg_row = row ; 2945msg_col = mp -> sb_msg_col ; 2946char * p = mp -> sb_text ; 2947msg_puts_display (p ,-1 ,mp -> sb_hl_id , true); 2948if (mp -> sb_eol || mp -> sb_next == NULL ) { 2949break ; 2950 } 2951mp = mp -> sb_next ; 2952 } 2953 2954return mp -> sb_next ; 2955} 2956 2957/// @return true when messages should be printed to stdout/stderr: 2958/// - "batch mode" ("silent mode", -es/-Es/-l) 2959/// - no UI and not embedded 2960/// - no ext_messages 2961int msg_use_printf (void ) 2962{ 2963return !embedded_mode && !ui_active ()&& !ui_has (kUIMessages ); 2964} 2965 2966/// Print a message when there is no valid screen. 2967static void msg_puts_printf (const char * str ,const ptrdiff_t maxlen ) 2968{ 2969const char * s = str ; 2970char buf [7 ]; 2971char * p ; 2972 2973if (on_print .type != kCallbackNone ) { 2974typval_T argv [1 ]; 2975argv [0 ].v_type = VAR_STRING ; 2976argv [0 ].v_lock = VAR_UNLOCKED ; 2977argv [0 ].vval .v_string = (char * )str ; 2978typval_T rettv = TV_INITIAL_VALUE ; 2979callback_call (& on_print ,1 ,argv ,& rettv ); 2980tv_clear (& rettv ); 2981return ; 2982 } 2983 2984while ((maxlen < 0 || s - str < maxlen )&& * s != NUL ) { 2985int len = utf_ptr2len (s ); 2986if (!(silent_mode && p_verbose == 0 )) { 2987// NL --> CR NL translation (for Unix, not for "--version") 2988p = & buf [0 ]; 2989if (* s == '\n' && !info_message && !silent_mode && !headless_mode ) { 2990* p ++ = '\r' ; 2991 } 2992memcpy (p ,s , (size_t )len ); 2993* (p + len )= NUL ; 2994if (info_message ) { 2995printf ("%s" ,buf ); 2996 }else { 2997fprintf (stderr ,"%s" ,buf ); 2998 } 2999 } 3000 3001int cw = utf_char2cells (utf_ptr2char (s )); 3002// primitive way to compute the current column 3003if (* s == '\r' || * s == '\n' ) { 3004msg_col = 0 ; 3005msg_didout = false; 3006 }else { 3007msg_col += cw ; 3008msg_didout = true; 3009 } 3010s += len ; 3011 } 3012} 3013 3014/// Show the more-prompt and handle the user response. 3015/// This takes care of scrolling back and displaying previously displayed text. 3016/// When at hit-enter prompt "typed_char" is the already typed character, 3017/// otherwise it's NUL. 3018/// 3019/// @return true when jumping ahead to "confirm_buttons". 3020static bool do_more_prompt (int typed_char ) 3021{ 3022static bool entered = false; 3023int used_typed_char = typed_char ; 3024int oldState = State ; 3025int c ; 3026bool retval = false; 3027bool to_redraw = false; 3028msgchunk_T * mp_last = NULL ; 3029msgchunk_T * mp ; 3030 3031// If headless mode is enabled and no input is required, this variable 3032// will be true. However If server mode is enabled, the message "--more--" 3033// should be displayed. 3034bool no_need_more = headless_mode && !embedded_mode && !ui_active (); 3035 3036// We get called recursively when a timer callback outputs a message. In 3037// that case don't show another prompt. Also when at the hit-Enter prompt 3038// and nothing was typed. 3039if (no_need_more || entered || (State == MODE_HITRETURN && typed_char == 0 )) { 3040return false; 3041 } 3042entered = true; 3043 3044if (typed_char == 'G' ) { 3045// "g<": Find first line on the last page. 3046mp_last = msg_sb_start (last_msgchunk ); 3047for (int i = 0 ;i < Rows - 2 && mp_last != NULL 3048&& mp_last -> sb_prev != NULL ;i ++ ) { 3049mp_last = msg_sb_start (mp_last -> sb_prev ); 3050 } 3051 } 3052 3053State = MODE_ASKMORE ; 3054setmouse (); 3055if (typed_char == NUL ) { 3056msg_moremsg (false); 3057 } 3058while (true) { 3059// Get a typed character directly from the user. 3060if (used_typed_char != NUL ) { 3061c = used_typed_char ;// was typed at hit-enter prompt 3062used_typed_char = NUL ; 3063 }else { 3064c = get_keystroke (resize_events ); 3065 } 3066 3067int toscroll = 0 ; 3068switch (c ) { 3069case BS :// scroll one line back 3070case K_BS : 3071case 'k' : 3072case K_UP : 3073toscroll = -1 ; 3074break ; 3075 3076case CAR :// one extra line 3077case NL : 3078case 'j' : 3079case K_DOWN : 3080toscroll = 1 ; 3081break ; 3082 3083case 'u' :// Up half a page 3084toscroll = - (Rows /2 ); 3085break ; 3086 3087case 'd' :// Down half a page 3088toscroll = Rows /2 ; 3089break ; 3090 3091case 'b' :// one page back 3092case Ctrl_B : 3093case K_PAGEUP : 3094toscroll = - (Rows - 1 ); 3095break ; 3096 3097case ' ' :// one extra page 3098case 'f' : 3099case Ctrl_F : 3100case K_PAGEDOWN : 3101case K_LEFTMOUSE : 3102toscroll = Rows - 1 ; 3103break ; 3104 3105case 'g' :// all the way back to the start 3106toscroll = -999999 ; 3107break ; 3108 3109case 'G' :// all the way to the end 3110toscroll = 999999 ; 3111lines_left = 999999 ; 3112break ; 3113 3114case ':' :// start new command line 3115if (!confirm_msg_used ) { 3116// Since got_int is set all typeahead will be flushed, but we 3117// want to keep this ':', remember that in a special way. 3118typeahead_noflush (':' ); 3119cmdline_row = Rows - 1 ;// put ':' on this line 3120skip_redraw = true;// skip redraw once 3121need_wait_return = false;// don't wait in main() 3122 } 3123FALLTHROUGH ; 3124case 'q' :// quit 3125case Ctrl_C : 3126case ESC : 3127if (confirm_msg_used ) { 3128// Jump to the choices of the dialog. 3129retval = true; 3130 }else { 3131got_int = true; 3132quit_more = true; 3133 } 3134// When there is some more output (wrapping line) display that 3135// without another prompt. 3136lines_left = Rows - 1 ; 3137break ; 3138 3139case K_EVENT : 3140// only resize_events are processed here 3141// Attempt to redraw the screen. sb_text doesn't support reflow 3142// so this only really works for vertical resize. 3143multiqueue_process_events (resize_events ); 3144to_redraw = true; 3145break ; 3146 3147default :// no valid response 3148msg_moremsg (true); 3149continue ; 3150 } 3151 3152// code assumes we only do one at a time 3153assert ((toscroll == 0 )|| !to_redraw ); 3154 3155if (toscroll != 0 || to_redraw ) { 3156if (toscroll < 0 || to_redraw ) { 3157// go to start of last line 3158if (mp_last == NULL ) { 3159mp = msg_sb_start (last_msgchunk ); 3160 }else if (mp_last -> sb_prev != NULL ) { 3161mp = msg_sb_start (mp_last -> sb_prev ); 3162 }else { 3163mp = NULL ; 3164 } 3165 3166// go to start of line at top of the screen 3167for (int i = 0 ;i < Rows - 2 && mp != NULL && mp -> sb_prev != NULL ;i ++ ) { 3168mp = msg_sb_start (mp -> sb_prev ); 3169 } 3170 3171if (mp != NULL && (mp -> sb_prev != NULL || to_redraw )) { 3172// Find line to be displayed at top 3173for (int i = 0 ;i > toscroll ;i -- ) { 3174if (mp == NULL || mp -> sb_prev == NULL ) { 3175break ; 3176 } 3177mp = msg_sb_start (mp -> sb_prev ); 3178if (mp_last == NULL ) { 3179mp_last = msg_sb_start (last_msgchunk ); 3180 }else { 3181mp_last = msg_sb_start (mp_last -> sb_prev ); 3182 } 3183 } 3184 3185if (toscroll == -1 && !to_redraw ) { 3186grid_ins_lines (& msg_grid ,0 ,1 ,Rows ,0 ,Columns ); 3187grid_clear (& msg_grid_adj ,0 ,1 ,0 ,Columns ,HL_ATTR (HLF_MSG )); 3188// display line at top 3189disp_sb_line (0 ,mp ); 3190 }else { 3191// redisplay all lines 3192// TODO(bfredl): this case is not optimized (though only concerns 3193// event fragmentation, not unnecessary scroll events). 3194grid_clear (& msg_grid_adj ,0 ,Rows ,0 ,Columns ,HL_ATTR (HLF_MSG )); 3195for (int i = 0 ;mp != NULL && i < Rows - 1 ;i ++ ) { 3196mp = disp_sb_line (i ,mp ); 3197msg_scrolled ++ ; 3198 } 3199to_redraw = false; 3200 } 3201toscroll = 0 ; 3202 } 3203 }else { 3204// First display any text that we scrolled back. 3205// if p_ch=0 we need to allocate a line for "press enter" messages! 3206if (cmdline_row >=Rows && !ui_has (kUIMessages )) { 3207msg_scroll_up (true, false); 3208msg_scrolled ++ ; 3209 } 3210while (toscroll > 0 && mp_last != NULL ) { 3211if (msg_do_throttle ()&& !msg_grid .throttled ) { 3212// Tricky: we redraw at one line higher than usual. Therefore 3213// the non-flushed area is one line larger. 3214msg_scrolled_at_flush -- ; 3215msg_grid_scroll_discount ++ ; 3216 } 3217// scroll up, display line at bottom 3218msg_scroll_up (true, false); 3219inc_msg_scrolled (); 3220grid_clear (& msg_grid_adj ,Rows - 2 ,Rows - 1 ,0 ,Columns ,HL_ATTR (HLF_MSG )); 3221mp_last = disp_sb_line (Rows - 2 ,mp_last ); 3222toscroll -- ; 3223 } 3224 } 3225 3226if (toscroll <=0 ) { 3227// displayed the requested text, more prompt again 3228grid_clear (& msg_grid_adj ,Rows - 1 ,Rows ,0 ,Columns ,HL_ATTR (HLF_MSG )); 3229msg_moremsg (false); 3230continue ; 3231 } 3232 3233// display more text, return to caller 3234lines_left = toscroll ; 3235 } 3236 3237break ; 3238 } 3239 3240// clear the --more-- message 3241grid_clear (& msg_grid_adj ,Rows - 1 ,Rows ,0 ,Columns ,HL_ATTR (HLF_MSG )); 3242redraw_cmdline = true; 3243clear_cmdline = false; 3244mode_displayed = false; 3245 3246State = oldState ; 3247setmouse (); 3248if (quit_more ) { 3249msg_row = Rows - 1 ; 3250msg_col = 0 ; 3251 } 3252 3253entered = false; 3254return retval ; 3255} 3256 3257static void msg_moremsg (bool full ) 3258{ 3259int attr = hl_combine_attr (HL_ATTR (HLF_MSG ),HL_ATTR (HLF_M )); 3260grid_line_start (& msg_grid_adj ,Rows - 1 ); 3261int len = grid_line_puts (0 ,_ ("-- More --" ),-1 ,attr ); 3262if (full ) { 3263len += grid_line_puts (len ,_ (" SPACE/d/j: screen/page/line down, b/u/k: up, q: quit " ), 3264-1 ,attr ); 3265 } 3266grid_line_cursor_goto (len ); 3267grid_line_flush (); 3268} 3269 3270/// Repeat the message for the current mode: MODE_ASKMORE, MODE_EXTERNCMD, 3271/// or confirm() prompt. 3272void repeat_message (void ) 3273{ 3274if (ui_has (kUIMessages )) { 3275return ; 3276 } 3277 3278if (State == MODE_ASKMORE ) { 3279msg_moremsg (true);// display --more-- message again 3280msg_row = Rows - 1 ; 3281 }else if ((State & MODE_CMDLINE )&& confirm_msg != NULL ) { 3282display_confirm_msg ();// display ":confirm" message again 3283msg_row = Rows - 1 ; 3284 }else if (State == MODE_EXTERNCMD ) { 3285ui_cursor_goto (msg_row ,msg_col );// put cursor back 3286 }else if (State == MODE_HITRETURN || State == MODE_SETWSIZE ) { 3287if (msg_row == Rows - 1 ) { 3288// Avoid drawing the "hit-enter" prompt below the previous one, 3289// overwrite it. Esp. useful when regaining focus and a 3290// FocusGained autocmd exists but didn't draw anything. 3291msg_didout = false; 3292msg_col = 0 ; 3293msg_clr_eos (); 3294 } 3295hit_return_msg (false); 3296msg_row = Rows - 1 ; 3297 } 3298} 3299 3300/// Clear from current message position to end of screen. 3301/// Skip this when ":silent" was used, no need to clear for redirection. 3302void msg_clr_eos (void ) 3303{ 3304if (msg_silent == 0 ) { 3305msg_clr_eos_force (); 3306 } 3307} 3308 3309/// Clear from current message position to end of screen. 3310/// Note: msg_col is not updated, so we remember the end of the message 3311/// for msg_check(). 3312void msg_clr_eos_force (void ) 3313{ 3314if (ui_has (kUIMessages )) { 3315return ; 3316 } 3317int msg_startcol = cmdmsg_rl ?0 :msg_col ; 3318int msg_endcol = cmdmsg_rl ?Columns - msg_col :Columns ; 3319 3320// TODO(bfredl): ugly, this state should already been validated at this 3321// point. But msg_clr_eos() is called in a lot of places. 3322if (msg_grid .chars && msg_row < msg_grid_pos ) { 3323msg_grid_validate (); 3324if (msg_row < msg_grid_pos ) { 3325msg_row = msg_grid_pos ; 3326 } 3327 } 3328 3329grid_clear (& msg_grid_adj ,msg_row ,msg_row + 1 ,msg_startcol ,msg_endcol ,HL_ATTR (HLF_MSG )); 3330grid_clear (& msg_grid_adj ,msg_row + 1 ,Rows ,0 ,Columns ,HL_ATTR (HLF_MSG )); 3331 3332redraw_cmdline = true;// overwritten the command line 3333if (msg_row < Rows - 1 || msg_col == 0 ) { 3334clear_cmdline = false;// command line has been cleared 3335mode_displayed = false;// mode cleared or overwritten 3336cmdline_was_last_drawn = false; 3337 } 3338} 3339 3340/// Clear the command line. 3341void msg_clr_cmdline (void ) 3342{ 3343msg_row = cmdline_row ; 3344msg_col = 0 ; 3345msg_clr_eos_force (); 3346} 3347 3348/// end putting a message on the screen 3349/// call wait_return() if the message does not fit in the available space 3350/// 3351/// @return true if wait_return() not called. 3352bool msg_end (void ) 3353{ 3354// If the string is larger than the window, 3355// or the ruler option is set and we run into it, 3356// we have to redraw the window. 3357// Do not do this if we are abandoning the file or editing the command line. 3358if (!exiting && need_wait_return && !(State & MODE_CMDLINE )) { 3359wait_return (false); 3360return false; 3361 } 3362 3363// NOTE: ui_flush() used to be called here. This had to be removed, as it 3364// inhibited substantial performance improvements. It is assumed that relevant 3365// callers invoke ui_flush() before going into CPU busywork, or restricted 3366// event processing after displaying a message to the user. 3367msg_ext_ui_flush (); 3368return true; 3369} 3370 3371/// Clear "msg_ext_chunks" before flushing so that ui_flush() does not re-emit 3372/// the same message recursively. 3373static Array * msg_ext_init_chunks (void ) 3374{ 3375Array * tofree = msg_ext_chunks ; 3376msg_ext_chunks = xcalloc (1 ,sizeof (* msg_ext_chunks )); 3377msg_col = 0 ; 3378return tofree ; 3379} 3380 3381void msg_ext_ui_flush (void ) 3382{ 3383if (!ui_has (kUIMessages )) { 3384msg_ext_kind = NULL ; 3385return ; 3386 }else if (msg_ext_skip_flush ) { 3387return ; 3388 } 3389 3390msg_ext_emit_chunk (); 3391if (msg_ext_chunks -> size > 0 ) { 3392Array * tofree = msg_ext_init_chunks (); 3393 3394ui_call_msg_show (cstr_as_string (msg_ext_kind ),* tofree ,msg_ext_overwrite ,msg_ext_history , 3395msg_ext_append ,msg_ext_id ,cstr_as_string (msg_ext_trigger )); 3396// clear info after emitting message. 3397if (msg_ext_history ) { 3398api_free_array (* tofree ); 3399 }else { 3400// Add to history as temporary message for "g<". 3401HlMessage msg = KV_INITIAL_VALUE ; 3402for (size_t i = 0 ;i < kv_size (* tofree );i ++ ) { 3403Object * chunk = kv_A (* tofree ,i ).data .array .items ; 3404kv_push (msg , ((HlMessageChunk ){chunk [1 ].data .string , (int )chunk [2 ].data .integer })); 3405xfree (chunk ); 3406 } 3407xfree (tofree -> items ); 3408msg_hist_add_multihl (msg , true); 3409 } 3410xfree (tofree ); 3411msg_ext_overwrite = false; 3412msg_ext_history = false; 3413msg_ext_append = false; 3414msg_ext_fast = true; 3415msg_ext_kind = NULL ; 3416// Consume the pre-allocated id, if the message did not get one from msg_multihl(). 3417if (msg_ext_id .type == kObjectTypeInteger && msg_ext_id .data .integer == msg_id_next ) { 3418msg_id_next ++ ; 3419 } 3420msg_ext_id = INTEGER_OBJ (msg_id_next ); 3421 } 3422} 3423 3424void msg_ext_flush_showmode (void ) 3425{ 3426// Showmode messages doesn't interrupt normal message flow, so we use 3427// separate event. Still reuse the same chunking logic, for simplicity. 3428// This is called unconditionally; check if we are emitting, or have 3429// emitted non-empty "content". 3430static bool clear = false; 3431if (ui_has (kUIMessages )&& (msg_ext_last_attr != -1 || clear )) { 3432clear = msg_ext_last_attr != -1 ; 3433msg_ext_emit_chunk (); 3434Array * tofree = msg_ext_init_chunks (); 3435ui_call_msg_showmode (* tofree ); 3436api_free_array (* tofree ); 3437xfree (tofree ); 3438 } 3439} 3440 3441/// If the written message runs into the shown command or ruler, we have to 3442/// wait for hit-return and redraw the window later. 3443void msg_check (void ) 3444{ 3445if (ui_has (kUIMessages )) { 3446return ; 3447 } 3448if (msg_row == Rows - 1 && msg_col >=sc_col ) { 3449need_wait_return = true; 3450redraw_cmdline = true; 3451 } 3452} 3453 3454/// May write a string to the redirection file. 3455/// 3456/// @param maxlen if -1, write the whole string, otherwise up to "maxlen" bytes. 3457static void redir_write (const char * const str ,const ptrdiff_t maxlen ) 3458{ 3459const char * s = str ; 3460 3461if (maxlen == 0 ) { 3462return ; 3463 } 3464 3465// Don't do anything for displaying prompts and the like. 3466if (redir_off ) { 3467return ; 3468 } 3469 3470// If 'verbosefile' is set prepare for writing in that file. 3471if (* p_vfile != NUL && verbose_fd == NULL ) { 3472verbose_open (); 3473 } 3474 3475if (redirecting ()) { 3476// If the string doesn't start with CR or NL, go to msg_col 3477if (* s != '\n' && * s != '\r' ) { 3478while (redir_col < msg_col ) { 3479if (capture_ga ) { 3480ga_concat_len (capture_ga ," " ,1 ); 3481 } 3482if (redir_reg ) { 3483write_reg_contents (redir_reg ," " ,1 , true); 3484 }else if (redir_vname ) { 3485var_redir_str (" " ,-1 ); 3486 }else if (redir_fd != NULL ) { 3487fputs (" " ,redir_fd ); 3488 } 3489if (verbose_fd != NULL ) { 3490fputs (" " ,verbose_fd ); 3491 } 3492redir_col ++ ; 3493 } 3494 } 3495 3496size_t len = maxlen == -1 ?strlen (s ) : (size_t )maxlen ; 3497if (capture_ga ) { 3498ga_concat_len (capture_ga ,str ,len ); 3499 } 3500if (redir_reg ) { 3501write_reg_contents (redir_reg ,s , (ssize_t )len , true); 3502 } 3503if (redir_vname ) { 3504var_redir_str (s , (int )maxlen ); 3505 } 3506 3507// Write and adjust the current column. 3508while (* s != NUL 3509&& (maxlen < 0 || (int )(s - str )< maxlen )) { 3510if (!redir_reg && !redir_vname && !capture_ga ) { 3511if (redir_fd != NULL ) { 3512putc (* s ,redir_fd ); 3513 } 3514 } 3515if (verbose_fd != NULL ) { 3516putc (* s ,verbose_fd ); 3517 } 3518if (* s == '\r' || * s == '\n' ) { 3519redir_col = 0 ; 3520 }else if (* s == '\t' ) { 3521redir_col += (8 - redir_col %8 ); 3522 }else { 3523redir_col ++ ; 3524 } 3525s ++ ; 3526 } 3527 3528if (msg_silent != 0 ) {// should update msg_col 3529msg_col = redir_col ; 3530 } 3531 } 3532} 3533 3534int redirecting (void ) 3535{ 3536return redir_fd != NULL || * p_vfile != NUL 3537|| redir_reg || redir_vname || capture_ga != NULL ; 3538} 3539 3540// Save and restore message kind when emitting a verbose message. 3541static const char * pre_verbose_kind = NULL ; 3542static const char * verbose_kind = "verbose" ; 3543 3544/// Before giving verbose message. 3545/// Must always be called paired with verbose_leave()! 3546void verbose_enter (void ) 3547{ 3548if (* p_vfile != NUL ) { 3549msg_silent ++ ; 3550 } 3551// Don't set the verbose kind if message continuity is wanted like with last_set_msg(). 3552if (!msg_ext_skip_verbose ) { 3553if (msg_ext_kind != verbose_kind ) { 3554pre_verbose_kind = msg_ext_kind ; 3555 } 3556msg_ext_set_kind ("verbose" ); 3557 } 3558msg_ext_skip_verbose = false; 3559} 3560 3561/// After giving verbose message. 3562/// Must always be called paired with verbose_enter()! 3563void verbose_leave (void ) 3564{ 3565if (* p_vfile != NUL ) { 3566if (-- msg_silent < 0 ) { 3567msg_silent = 0 ; 3568 } 3569 } 3570if (pre_verbose_kind != NULL ) { 3571msg_ext_set_kind (pre_verbose_kind ); 3572pre_verbose_kind = NULL ; 3573 } 3574} 3575 3576/// Like verbose_enter() and set msg_scroll when displaying the message. 3577void verbose_enter_scroll (void ) 3578{ 3579verbose_enter (); 3580if (* p_vfile == NUL ) { 3581// always scroll up, don't overwrite 3582msg_scroll = true; 3583 } 3584} 3585 3586/// Like verbose_leave() and set cmdline_row when displaying the message. 3587void verbose_leave_scroll (void ) 3588{ 3589verbose_leave (); 3590if (* p_vfile == NUL ) { 3591cmdline_row = msg_row ; 3592 } 3593} 3594 3595/// Called when 'verbosefile' is set: stop writing to the file. 3596void verbose_stop (void ) 3597{ 3598if (verbose_fd != NULL ) { 3599fclose (verbose_fd ); 3600verbose_fd = NULL ; 3601 } 3602verbose_did_open = false; 3603} 3604 3605/// Open the file 'verbosefile'. 3606/// 3607/// @return FAIL or OK. 3608int verbose_open (void ) 3609{ 3610if (verbose_fd == NULL && !verbose_did_open ) { 3611// Only give the error message once. 3612verbose_did_open = true; 3613 3614verbose_fd = os_fopen (p_vfile ,"a" ); 3615if (verbose_fd == NULL ) { 3616semsg (_ (e_notopen ),p_vfile ); 3617return FAIL ; 3618 } 3619 } 3620return OK ; 3621} 3622 3623/// Give a warning message (for searching). 3624/// Use 'w' highlighting and may repeat the message after redrawing 3625void give_warning (const char * message ,bool hl ,bool hist ) 3626FUNC_ATTR_NONNULL_ARG (1 ) 3627{ 3628// Don't do this for ":silent". 3629if (msg_silent != 0 ) { 3630return ; 3631 } 3632 3633bool save_msg_hist_off = msg_hist_off ; 3634msg_hist_off = !hist ; 3635 3636// Don't want a hit-enter prompt here. 3637no_wait_return ++ ; 3638 3639set_vim_var_string (VV_WARNINGMSG ,message ,-1 ); 3640XFREE_CLEAR (keep_msg ); 3641if (hl ) { 3642keep_msg_hl_id = HLF_W ; 3643 }else { 3644keep_msg_hl_id = 0 ; 3645 } 3646 3647if (msg_ext_kind == NULL ) { 3648msg_ext_set_kind ("wmsg" ); 3649 } 3650 3651if (msg (message ,keep_msg_hl_id )&& msg_scrolled == 0 ) { 3652set_keep_msg (message ,keep_msg_hl_id ); 3653 } 3654msg_didout = false;// Overwrite this message. 3655msg_nowait = true;// Don't wait for this message. 3656msg_col = 0 ; 3657 3658no_wait_return -- ; 3659msg_hist_off = save_msg_hist_off ; 3660} 3661 3662/// Shows a warning, with optional highlighting. 3663/// 3664/// @param hl enable highlighting 3665/// @param fmt printf-style format message 3666/// 3667/// @see smsg 3668/// @see semsg 3669void swmsg (bool hl ,const char * const fmt , ...) 3670FUNC_ATTR_PRINTF (2 ,3 ) 3671{ 3672va_list args ; 3673 3674va_start (args ,fmt ); 3675vim_vsnprintf (IObuff ,IOSIZE ,fmt ,args ); 3676va_end (args ); 3677 3678give_warning (IObuff ,hl , true); 3679} 3680 3681/// Advance msg cursor to column "col". 3682void msg_advance (int col ) 3683{ 3684if (msg_silent != 0 ) {// nothing to advance to 3685msg_col = col ;// for redirection, may fill it up later 3686return ; 3687 } 3688col = MIN (col ,Columns - 1 );// not enough room 3689while (msg_col < col ) { 3690msg_putchar (' ' ); 3691 } 3692} 3693 3694/// Display the ":confirm" message. Also called from do_dialog() and when screen resized. 3695void display_confirm_msg (void ) 3696{ 3697// Avoid that 'q' at the more prompt truncates the message here. 3698confirm_msg_used ++ ; 3699if (confirm_msg != NULL ) { 3700msg_ext_set_kind ("confirm" ); 3701msg_puts_hl (confirm_msg ,HLF_M , false); 3702 } 3703confirm_msg_used -- ; 3704} 3705 3706/// Only for legacy UI (`!ui_has(kUIMessages)`): Pause to display a message for `ms` milliseconds. 3707/// 3708/// TODO(justinmk): Most of these cases may not be needed after "ui2"... 3709void msg_delay (uint64_t ms ,bool ignoreinput ) 3710{ 3711if (ui_has (kUIMessages )) { 3712return ; 3713 } 3714 3715if (nvim_testing ) { 3716// XXX: Reduce non-functional (UI only) delay in tests/CI. 3717ms = 100 ; 3718 } 3719 3720DLOG ("%" PRIu64 " ms%s" ,ms ,nvim_testing ?" (skipped by NVIM_TEST)" :"" ); 3721ui_flush (); 3722os_delay (ms ,ignoreinput ); 3723} 3724 3725/// Check if there should be a delay to allow the user to see a message. 3726/// 3727/// Used before clearing or redrawing the screen or the command line. 3728void msg_check_for_delay (bool check_msg_scroll ) 3729{ 3730if ((emsg_on_display || (check_msg_scroll && msg_scroll )) 3731&& !did_wait_return && emsg_silent == 0 && !in_assert_fails && !ui_has (kUIMessages )) { 3732msg_delay (1006 , true); 3733emsg_on_display = false; 3734if (check_msg_scroll ) { 3735msg_scroll = false; 3736 } 3737 } 3738}