robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// autocmd.c: Autocommand related functions 2 3#include <assert.h> 4#include <stddef.h> 5#include <stdint.h> 6#include <stdio.h> 7#include <stdlib.h> 8#include <string.h> 9 10#include "nvim/api/private/converter.h" 11#include "nvim/autocmd.h" 12#include "nvim/autocmd_defs.h" 13#include "nvim/buffer.h" 14#include "nvim/charset.h" 15#include "nvim/cmdexpand_defs.h" 16#include "nvim/context.h" 17#include "nvim/cursor.h" 18#include "nvim/errors.h" 19#include "nvim/eval.h" 20#include "nvim/eval/typval.h" 21#include "nvim/eval/userfunc.h" 22#include "nvim/eval/vars.h" 23#include "nvim/event/loop.h" 24#include "nvim/event/multiqueue.h" 25#include "nvim/ex_docmd.h" 26#include "nvim/ex_eval.h" 27#include "nvim/fileio.h" 28#include "nvim/gettext_defs.h" 29#include "nvim/globals.h" 30#include "nvim/grid.h" 31#include "nvim/grid_defs.h" 32#include "nvim/hashtab.h" 33#include "nvim/highlight_defs.h" 34#include "nvim/input.h" 35#include "nvim/input_defs.h" 36#include "nvim/insexpand.h" 37#include "nvim/lua/executor.h" 38#include "nvim/main.h" 39#include "nvim/map_defs.h" 40#include "nvim/mbyte.h" 41#include "nvim/memory.h" 42#include "nvim/message.h" 43#include "nvim/option.h" 44#include "nvim/option_defs.h" 45#include "nvim/option_vars.h" 46#include "nvim/os/input.h" 47#include "nvim/os/os.h" 48#include "nvim/os/os_defs.h" 49#include "nvim/os/time.h" 50#include "nvim/os/time_defs.h" 51#include "nvim/path.h" 52#include "nvim/profile.h" 53#include "nvim/regexp.h" 54#include "nvim/runtime.h" 55#include "nvim/runtime_defs.h" 56#include "nvim/search.h" 57#include "nvim/state.h" 58#include "nvim/state_defs.h" 59#include "nvim/strings.h" 60#include "nvim/types_defs.h" 61#include "nvim/ui.h" 62#include "nvim/ui_compositor.h" 63#include "nvim/vim_defs.h" 64#include "nvim/window.h" 65#include "nvim/winfloat.h" 66 67#include "auevents_name_map.generated.h" 68#include "autocmd.c.generated.h" 69 70static const char e_autocommand_nesting_too_deep [] 71= N_ ("E218: Autocommand nesting too deep" ); 72 73// Naming Conventions: 74// - general autocmd behavior start with au_ 75// - AutoCmd start with aucmd_ 76// - AutoPat start with aupat_ 77// - Groups start with augroup_ 78// - Events start with event_ 79 80// The autocommands are stored in a contiguous vector for each event. 81// 82// The order of AutoCmds is important, this is the order in which they 83// were defined and will have to be executed. 84// 85// To avoid having to match the pattern too often, patterns are reference 86// counted and reused for consecutive autocommands. 87 88// Code for automatic commands. 89static AutoPatCmd * active_apc_list = NULL ;// stack of active autocommands 90 91/// Window handle for `ev.win`. Unlike autocmd_bufnr/_match this needn't be a 92/// global: only au_callback() reads it. 93static handle_T autocmd_winid = 0 ; 94 95// ID for associating autocmds created via nvim_create_autocmd 96// Used to delete autocmds from nvim_del_autocmd 97static int next_augroup_id = 1 ; 98 99// use get_deleted_augroup() to get this 100static const char * deleted_augroup = NULL ; 101 102// The ID of the current group. 103static int current_augroup = AUGROUP_DEFAULT ; 104 105// Whether we need to delete marked patterns. 106// While deleting autocmds, they aren't actually remover, just marked. 107static bool au_need_clean = false; 108 109static int autocmd_blocked = 0 ;// block all autocmds 110 111static bool autocmd_nested = false; 112static bool autocmd_include_groups = false; 113 114static bool termresponse_changed = false; 115static uint64_t termresponse_chan_id = 0 ; 116 117// Map of autocmd group names and ids. 118// name -> ID 119// ID -> name 120static Map (String ,int )map_augroup_name_to_id = MAP_INIT ; 121static Map (int ,String )map_augroup_id_to_name = MAP_INIT ; 122 123void autocmd_init (void ) 124{ 125deferred_events = multiqueue_new_child (main_loop .events ); 126} 127 128#ifdef EXITFREE 129void autocmd_free_all_mem (void ) 130{ 131multiqueue_free (deferred_events ); 132} 133#endif 134 135static void augroup_map_del (int id ,const char * name ) 136{ 137if (name != NULL ) { 138String key ; 139map_del (String ,int )(& map_augroup_name_to_id ,cstr_as_string (name ),& key ); 140api_free_string (key ); 141 } 142if (id > 0 ) { 143String mapped = map_del (int ,String )(& map_augroup_id_to_name ,id ,NULL ); 144api_free_string (mapped ); 145 } 146} 147 148static inline const char * get_deleted_augroup (void )FUNC_ATTR_ALWAYS_INLINE 149{ 150if (deleted_augroup == NULL ) { 151deleted_augroup = _ ("--Deleted--" ); 152 } 153return deleted_augroup ; 154} 155 156static void au_show_for_all_events (int group ,const char * pat ) 157{ 158FOR_ALL_AUEVENTS (event ) { 159au_show_for_event (group ,event ,pat ); 160 } 161} 162 163static void au_show_for_event (int group ,event_T event ,const char * pat ) 164FUNC_ATTR_NONNULL_ALL 165{ 166AutoCmdVec * const acs = & autocmds [(int )event ]; 167// Return early if there are no autocmds for this event 168if (kv_size (* acs )== 0 ) { 169return ; 170 } 171 172// Empty pattern shows all autocommands for this event 173int patlen = 0 ; 174if (* pat != NUL ) { 175patlen = (int )aucmd_span_pattern (pat ,& pat ); 176if (patlen == 0 ) {// Don't show if it contains only commas 177return ; 178 } 179 } 180 181char buflocal_pat [BUFLOCAL_PAT_LEN ];// for "<buffer=X>" 182int last_group = AUGROUP_ERROR ; 183const char * last_group_name = NULL ; 184 185// Loop through all the specified patterns. 186do { 187AutoPat * last_ap = NULL ; 188const char * endpat = pat + patlen ; 189 190// detect special <buffer[=X]> buffer-local patterns 191if (aupat_is_buflocal (pat ,patlen )) { 192// normalize pat into standard "<buffer>#N" form 193aupat_normalize_buflocal_pat (buflocal_pat ,pat ,patlen ,aupat_get_buflocal_nr (pat ,patlen )); 194pat = buflocal_pat ; 195patlen = (int )strlen (buflocal_pat ); 196 } 197 198for (size_t i = 0 ;i < kv_size (* acs );i ++ ) { 199AutoCmd * const ac = & kv_A (* acs ,i ); 200 201// Skip deleted autocommands. 202if (ac -> pat == NULL ) { 203continue ; 204 } 205 206// Accept a pattern when: 207// - a group was specified and it's that group 208// - the length of the pattern matches 209// - the pattern matches. 210// For <buffer[=X]>, this condition works because we normalize 211// all buffer-local patterns. 212if ((group != AUGROUP_ALL && ac -> pat -> group != group ) 213|| (patlen 214&& (ac -> pat -> patlen != patlen || strncmp (pat ,ac -> pat -> pat , (size_t )patlen )!= 0 ))) { 215continue ; 216 } 217 218// Show event name and group only if one of them changed. 219if (ac -> pat -> group != last_group ) { 220last_group = ac -> pat -> group ; 221last_group_name = augroup_name (ac -> pat -> group ); 222 223if (got_int ) { 224return ; 225 } 226 227msg_putchar ('\n' ); 228if (got_int ) { 229return ; 230 } 231 232// When switching groups, we need to show the new group information. 233// show the group name, if it's not the default group 234if (ac -> pat -> group != AUGROUP_DEFAULT ) { 235if (last_group_name == NULL ) { 236msg_puts_hl (get_deleted_augroup (),HLF_E , false); 237 }else { 238msg_puts_hl (last_group_name ,HLF_T , false); 239 } 240msg_puts (" " ); 241 } 242// show the event name 243msg_puts_hl (event_nr2name (event ),HLF_T , false); 244 } 245 246// Show pattern only if it changed. 247if (last_ap != ac -> pat ) { 248last_ap = ac -> pat ; 249 250msg_putchar ('\n' ); 251if (got_int ) { 252return ; 253 } 254 255msg_advance (4 ); 256msg_outtrans (ac -> pat -> pat ,0 , false); 257 } 258 259if (got_int ) { 260return ; 261 } 262 263if (msg_col >=14 ) { 264msg_putchar ('\n' ); 265 } 266msg_advance (14 ); 267if (got_int ) { 268return ; 269 } 270 271char * handler_str = aucmd_handler_to_string (ac ); 272if (ac -> desc != NULL ) { 273size_t msglen = 100 ; 274char * msg = xmallocz (msglen ); 275if (ac -> handler_cmd ) { 276snprintf (msg ,msglen ,"%s [%s]" ,handler_str ,ac -> desc ); 277 }else { 278msg_puts_hl (handler_str ,HLF_8 , false); 279snprintf (msg ,msglen ," [%s]" ,ac -> desc ); 280 } 281msg_outtrans (msg ,0 , false); 282XFREE_CLEAR (msg ); 283 }else if (ac -> handler_cmd ) { 284msg_outtrans (handler_str ,0 , false); 285 }else { 286msg_puts_hl (handler_str ,HLF_8 , false); 287 } 288XFREE_CLEAR (handler_str ); 289if (p_verbose > 0 ) { 290last_set_msg (ac -> script_ctx ); 291 } 292 293if (got_int ) { 294return ; 295 } 296 } 297 298patlen = (int )aucmd_span_pattern (endpat ,& pat ); 299 }while (patlen ); 300} 301 302// Delete autocommand. 303static void aucmd_del (AutoCmd * ac ) 304{ 305if (ac -> pat != NULL && -- ac -> pat -> refcount == 0 ) { 306XFREE_CLEAR (ac -> pat -> pat ); 307vim_regfree (ac -> pat -> reg_prog ); 308xfree (ac -> pat ); 309 } 310ac -> pat = NULL ; 311if (ac -> handler_cmd ) { 312XFREE_CLEAR (ac -> handler_cmd ); 313 }else { 314callback_free (& ac -> handler_fn ); 315 } 316XFREE_CLEAR (ac -> desc ); 317 318au_need_clean = true; 319} 320 321void aucmd_del_for_event_and_group (event_T event ,int group ) 322{ 323AutoCmdVec * const acs = & autocmds [(int )event ]; 324for (size_t i = 0 ;i < kv_size (* acs );i ++ ) { 325AutoCmd * const ac = & kv_A (* acs ,i ); 326if (ac -> pat != NULL && ac -> pat -> group == group ) { 327aucmd_del (ac ); 328 } 329 } 330 331au_cleanup (); 332} 333 334/// Cleanup autocommands that have been deleted. 335/// This is only done when not executing autocommands. 336static void au_cleanup (void ) 337{ 338if (autocmd_busy || !au_need_clean ) { 339return ; 340 } 341 342// Loop over all events. 343FOR_ALL_AUEVENTS (event ) { 344// Loop over all autocommands. 345AutoCmdVec * const acs = & autocmds [(int )event ]; 346size_t nsize = 0 ; 347for (size_t i = 0 ;i < kv_size (* acs );i ++ ) { 348AutoCmd * const ac = & kv_A (* acs ,i ); 349if (nsize != i ) { 350kv_A (* acs ,nsize )= * ac ; 351 } 352if (ac -> pat != NULL ) { 353nsize ++ ; 354 } 355 } 356if (nsize == 0 ) { 357kv_destroy (* acs ); 358 }else { 359acs -> size = nsize ; 360 } 361 } 362 363au_need_clean = false; 364} 365 366AutoCmdVec * au_get_autocmds_for_event (event_T event ) 367FUNC_ATTR_PURE 368{ 369return & autocmds [(int )event ]; 370} 371 372// Called when buffer is freed, to remove/invalidate related buffer-local autocmds. 373void aubuflocal_remove (buf_T * buf ) 374{ 375// invalidate currently executing autocommands 376for (AutoPatCmd * apc = active_apc_list ;apc != NULL ;apc = apc -> next ) { 377if (buf -> b_fnum == apc -> arg_bufnr ) { 378apc -> arg_bufnr = 0 ; 379 } 380 } 381 382// invalidate buflocals looping through events 383FOR_ALL_AUEVENTS (event ) { 384AutoCmdVec * const acs = & autocmds [(int )event ]; 385for (size_t i = 0 ;i < kv_size (* acs );i ++ ) { 386AutoCmd * const ac = & kv_A (* acs ,i ); 387if (ac -> pat == NULL || ac -> pat -> buflocal_nr != buf -> b_fnum ) { 388continue ; 389 } 390 391aucmd_del (ac ); 392 393if (p_verbose >=6 ) { 394verbose_enter (); 395smsg (0 ,_ ("auto-removing autocommand: %s <buffer=%d>" ),event_nr2name (event ),buf -> b_fnum ); 396verbose_leave (); 397 } 398 } 399 } 400au_cleanup (); 401} 402 403// Add an autocmd group name or return existing group matching name. 404// Return its ID. 405int augroup_add (const char * name ) 406{ 407assert (STRICMP (name ,"end" )!= 0 ); 408 409int existing_id = augroup_find (name ); 410if (existing_id > 0 ) { 411assert (existing_id != AUGROUP_DELETED ); 412return existing_id ; 413 } 414 415if (existing_id == AUGROUP_DELETED ) { 416augroup_map_del (existing_id ,name ); 417 } 418 419int next_id = next_augroup_id ++ ; 420String name_key = cstr_to_string (name ); 421String name_val = cstr_to_string (name ); 422map_put (String ,int )(& map_augroup_name_to_id ,name_key ,next_id ); 423map_put (int ,String )(& map_augroup_id_to_name ,next_id ,name_val ); 424 425return next_id ; 426} 427 428void augroup_del_by_id (int id ) 429{ 430char * name = id <=0 ?NULL :augroup_name (id ); 431if (name == NULL ) { 432semsg (_ ("E367: No such group id: %d" ),id ); 433 }else { 434// NB: this can still error, but the error might be "semantic" like "-- Deleted --" 435augroup_del (name ,id , false); 436 } 437} 438 439/// Delete the augroup that matches name. 440/// @param stupid_legacy_mode bool: This parameter determines whether to run the augroup 441/// deletion in the same fashion as `:augroup! {name}` where if there are any remaining 442/// autocmds left in the augroup, it will change the name of the augroup to `--- DELETED ---` 443/// but leave the autocmds existing. These are _separate_ augroups, so if you do this for 444/// multiple augroups, you will have a bunch of `--- DELETED ---` augroups at the same time. 445/// There is no way, as far as I could tell, how to actually delete them at this point as a user 446/// 447/// I did not consider this good behavior, so now when NOT in stupid_legacy_mode, we actually 448/// delete these groups and their commands, like you would expect (and don't leave hanging 449/// `--- DELETED ---` groups around) 450/// @param id_for_error only to provide context for an error message: 451/// if >= 0, we tried to look up the group by id 452/// if < 0, only use `name` for error 453void augroup_del (char * name ,int id_for_error ,bool stupid_legacy_mode ) 454{ 455int group = augroup_find (name ); 456if (group == AUGROUP_ERROR ) {// the group doesn't exist 457if (id_for_error > 0 ) { 458semsg (_ ("E367: No such group id: %d \"%s\"" ),id_for_error ,name ); 459 }else { 460semsg (_ ("E367: No such group: \"%s\"" ),name ); 461 } 462return ; 463 }else if (group == current_augroup ) { 464emsg (_ ("E936: Cannot delete the current group" )); 465return ; 466 } 467 468if (stupid_legacy_mode ) { 469FOR_ALL_AUEVENTS (event ) { 470AutoCmdVec * const acs = & autocmds [(int )event ]; 471for (size_t i = 0 ;i < kv_size (* acs );i ++ ) { 472AutoPat * const ap = kv_A (* acs ,i ).pat ; 473if (ap != NULL && ap -> group == group ) { 474give_warning (_ ("W19: Deleting augroup that is still in use" ), true, true); 475map_put (String ,int )(& map_augroup_name_to_id ,cstr_as_string (name ),AUGROUP_DELETED ); 476augroup_map_del (ap -> group ,NULL ); 477return ; 478 } 479 } 480 } 481 }else { 482FOR_ALL_AUEVENTS (event ) { 483AutoCmdVec * const acs = & autocmds [(int )event ]; 484for (size_t i = 0 ;i < kv_size (* acs );i ++ ) { 485AutoCmd * const ac = & kv_A (* acs ,i ); 486if (ac -> pat != NULL && ac -> pat -> group == group ) { 487aucmd_del (ac ); 488 } 489 } 490 } 491 } 492 493// Remove the group because it's not currently in use. 494augroup_map_del (group ,name ); 495au_cleanup (); 496} 497 498/// Find the ID of an autocmd group name. 499/// 500/// @param name augroup name 501/// 502/// @return the ID or AUGROUP_ERROR (< 0) for error. 503int augroup_find (const char * name ) 504FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 505{ 506int existing_id = map_get (String ,int )(& map_augroup_name_to_id ,cstr_as_string (name )); 507if (existing_id == AUGROUP_DELETED ) { 508return existing_id ; 509 } 510 511if (existing_id > 0 ) { 512return existing_id ; 513 } 514 515return AUGROUP_ERROR ; 516} 517 518/// Gets the name for a particular group. 519char * augroup_name (int group ) 520{ 521assert (group != 0 ); 522 523if (group == AUGROUP_DELETED ) { 524return (char * )get_deleted_augroup (); 525 } 526 527if (group == AUGROUP_ALL ) { 528group = current_augroup ; 529 } 530 531// next_augroup_id is the "source of truth" about what autocmds have existed 532// 533// The map_size is not the source of truth because groups can be removed from 534// the map. When this happens, the map size is reduced. That's why this function 535// relies on next_augroup_id instead. 536 537// "END" is always considered the last augroup ID. 538// Used for expand_get_event_name and expand_get_augroup_name 539if (group == next_augroup_id ) { 540return "END" ; 541 } 542 543// If it's larger than the largest group, then it doesn't have a name 544if (group > next_augroup_id ) { 545return NULL ; 546 } 547 548String key = map_get (int ,String )(& map_augroup_id_to_name ,group ); 549if (key .data != NULL ) { 550return key .data ; 551 } 552 553// If it's not in the map anymore, then it must have been deleted. 554return (char * )get_deleted_augroup (); 555} 556 557/// Return true if augroup "name" exists. 558/// 559/// @param name augroup name 560bool augroup_exists (const char * name ) 561FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 562{ 563return augroup_find (name )> 0 ; 564} 565 566/// ":augroup {name}". 567void do_augroup (char * arg ,bool del_group ) 568{ 569if (del_group ) { 570if (* arg == NUL ) { 571emsg (_ (e_argreq )); 572 }else { 573augroup_del (arg ,-1 , true); 574 } 575 }else if (STRICMP (arg ,"end" )== 0 ) {// ":aug end": back to group 0 576current_augroup = AUGROUP_DEFAULT ; 577 }else if (* arg ) {// ":aug xxx": switch to group xxx 578current_augroup = augroup_add (arg ); 579 }else {// ":aug": list the group names 580msg_start (); 581msg_ext_set_kind ("list_cmd" ); 582 583String name ; 584int value ; 585map_foreach (& map_augroup_name_to_id ,name ,value , { 586if (value > 0 ) { 587msg_puts (name .data ); 588 }else { 589msg_puts (augroup_name (value )); 590 } 591 592msg_puts (" " ); 593 }); 594 595msg_clr_eos (); 596msg_end (); 597 } 598} 599 600#ifdef EXITFREE 601void free_all_autocmds (void ) 602{ 603FOR_ALL_AUEVENTS (event ) { 604AutoCmdVec * const acs = & autocmds [(int )event ]; 605for (size_t i = 0 ;i < kv_size (* acs );i ++ ) { 606aucmd_del (& kv_A (* acs ,i )); 607 } 608kv_destroy (* acs ); 609au_need_clean = false; 610 } 611 612// Delete the augroup_map, including free the data 613String name ; 614map_foreach_key (& map_augroup_name_to_id ,name , { 615api_free_string (name ); 616 }) 617map_destroy (String ,& map_augroup_name_to_id ); 618 619map_foreach_value (& map_augroup_id_to_name ,name , { 620api_free_string (name ); 621 }) 622map_destroy (int ,& map_augroup_id_to_name ); 623 624// ctx_win[] is freed in win_free_all() 625} 626#endif 627 628/// Return the event number for event name "start". 629/// Return NUM_EVENTS if the event name was not found. 630/// Return a pointer to the next event name in "end". 631event_T event_name2nr (const char * start ,char ** end ) 632{ 633const char * p ; 634 635// the event name ends with end of line, '|', a blank or a comma 636for (p = start ;* p && !ascii_iswhite (* p )&& * p != ',' && * p != '|' ;p ++ ) {} 637 638int hash_idx = event_name2nr_hash (start , (size_t )(p - start )); 639if (* p == ',' ) { 640p ++ ; 641 } 642* end = (char * )p ; 643if (hash_idx < 0 ) { 644return NUM_EVENTS ; 645 } 646return (event_T )abs (event_names [event_hash [hash_idx ]].event ); 647} 648 649/// Return the event number for event name "str". 650/// Return NUM_EVENTS if the event name was not found. 651event_T event_name2nr_str (String str ) 652{ 653int hash_idx = event_name2nr_hash (str .data ,str .size ); 654if (hash_idx < 0 ) { 655return NUM_EVENTS ; 656 } 657return (event_T )abs (event_names [event_hash [hash_idx ]].event ); 658} 659 660/// Return the name for event 661/// 662/// @param[in] event Event to return name for. 663/// 664/// @return Event name, static string. Returns "Unknown" for unknown events. 665const char * event_nr2name (event_T event ) 666FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_CONST 667{ 668return event >=0 && event < NUM_EVENTS ?event_names [event ].name :"Unknown" ; 669} 670 671/// Return true if "event" is included in 'eventignore(win)'. 672/// 673/// @param event event to check 674bool event_ignored (event_T event ,char * ei ) 675FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 676{ 677bool ignored = false; 678while (* ei != NUL ) { 679bool unignore = * ei == '-' ; 680ei += unignore ; 681if (STRNICMP (ei ,"all" ,3 )== 0 && (ei [3 ]== NUL || ei [3 ]== ',' )) { 682ignored = ei == p_ei || event_names [event ].event <=0 ; 683ei += 3 + (ei [3 ]== ',' ); 684 }else if (event_name2nr (ei ,& ei )== event ) { 685if (unignore ) { 686return false; 687 } 688ignored = true; 689 } 690 } 691 692return ignored ; 693} 694 695/// Return OK when the contents of 'eventignore' or 'eventignorewin' is valid, 696/// FAIL otherwise. 697int check_ei (char * ei ,bool win ) 698{ 699while (* ei ) { 700if (STRNICMP (ei ,"all" ,3 )== 0 && (ei [3 ]== NUL || ei [3 ]== ',' )) { 701ei += 3 + (ei [3 ]== ',' ); 702 }else { 703ei += (* ei == '-' ); 704event_T event = event_name2nr (ei ,& ei ); 705if (event == NUM_EVENTS || (win && event_names [event ].event > 0 )) { 706return FAIL ; 707 } 708 } 709 } 710 711return OK ; 712} 713 714// Add "what" to 'eventignore' to skip loading syntax highlighting for every 715// buffer loaded into the window. "what" must start with a comma. 716// Returns the old value of 'eventignore' in allocated memory. 717char * au_event_disable (char * what ) 718{ 719size_t p_ei_len = strlen (p_ei ); 720char * save_ei = xmemdupz (p_ei ,p_ei_len ); 721char * new_ei = xstrnsave (p_ei ,p_ei_len + strlen (what )); 722if (* what == ',' && * p_ei == NUL ) { 723STRCPY (new_ei ,what + 1 ); 724 }else { 725STRCPY (new_ei + p_ei_len ,what ); 726 } 727set_option_direct (kOptEventignore ,CSTR_AS_OBJ (new_ei ),0 ,SID_NONE ); 728xfree (new_ei ); 729return save_ei ; 730} 731 732void au_event_restore (char * old_ei ) 733{ 734if (old_ei != NULL ) { 735set_option_direct (kOptEventignore ,CSTR_AS_OBJ (old_ei ),0 ,SID_NONE ); 736xfree (old_ei ); 737 } 738} 739 740// Implements :autocmd. 741// Defines an autocmd (does not execute; cf. apply_autocmds_group). 742// 743// Can be used in the following ways: 744// 745// :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that 746// will be automatically executed for <event> 747// when editing a file matching <pat>, in 748// the current group. 749// :autocmd <event> <pat> Show the autocommands associated with 750// <event> and <pat>. 751// :autocmd <event> Show the autocommands associated with 752// <event>. 753// :autocmd Show all autocommands. 754// :autocmd! <event> <pat> <cmd> Remove all autocommands associated with 755// <event> and <pat>, and add the command 756// <cmd>, for the current group. 757// :autocmd! <event> <pat> Remove all autocommands associated with 758// <event> and <pat> for the current group. 759// :autocmd! <event> Remove all autocommands associated with 760// <event> for the current group. 761// :autocmd! Remove ALL autocommands for the current 762// group. 763// 764// Multiple events and patterns may be given separated by commas. Here are 765// some examples: 766// :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic 767// :autocmd bufleave * set tw=79 nosmartindent ic infercase 768// 769// :autocmd * *.c show all autocommands for *.c files. 770// 771// Mostly a {group} argument can optionally appear before <event>. 772void do_autocmd (exarg_T * eap ,char * arg_in ,int forceit ) 773{ 774char * arg = arg_in ; 775char * envpat = NULL ; 776char * cmd ; 777bool cmd_need_free = false; 778bool nested = false; 779bool once = false; 780int group ; 781 782if (* arg == '|' ) { 783eap -> nextcmd = arg + 1 ; 784arg = "" ; 785group = AUGROUP_ALL ;// no argument, use all groups 786 }else { 787// Check for a legal group name. If not, use AUGROUP_ALL. 788group = arg_augroup_get (& arg ); 789 } 790 791// Scan over the events. 792// If we find an illegal name, return here, don't do anything. 793char * pat = arg_event_skip (arg ,group != AUGROUP_ALL ); 794if (pat == NULL ) { 795return ; 796 } 797 798pat = skipwhite (pat ); 799if (* pat == '|' ) { 800eap -> nextcmd = pat + 1 ; 801pat = "" ; 802cmd = "" ; 803 }else { 804// Scan over the pattern. Put a NUL at the end. 805cmd = pat ; 806while (* cmd && (!ascii_iswhite (* cmd )|| cmd [-1 ]== '\\' )) { 807cmd ++ ; 808 } 809if (* cmd ) { 810* cmd ++ = NUL ; 811 } 812 813// Expand environment variables in the pattern. 814if (vim_strchr (pat ,'$' )!= NULL || vim_strchr (pat ,'~' )!= NULL ) { 815envpat = expand_env_save (pat ); 816if (envpat != NULL ) { 817pat = envpat ; 818 } 819 } 820 821cmd = skipwhite (cmd ); 822 823bool invalid_flags = false; 824for (size_t i = 0 ;i < 2 ;i ++ ) { 825if (* cmd == NUL ) { 826continue ; 827 } 828 829invalid_flags |=arg_autocmd_flag_get (& once ,& cmd ,"++once" ,6 ); 830invalid_flags |=arg_autocmd_flag_get (& nested ,& cmd ,"++nested" ,8 ); 831 832// Check the deprecated "nested" flag. 833invalid_flags |=arg_autocmd_flag_get (& nested ,& cmd ,"nested" ,6 ); 834 } 835 836if (invalid_flags ) { 837 gotoerr_exit ; 838 } 839 840// Find the start of the commands. 841// Expand <sfile> in it. 842if (* cmd != NUL ) { 843cmd = expand_sfile (cmd ); 844if (cmd == NULL ) {// some error 845 gotoerr_exit ; 846 } 847cmd_need_free = true; 848 } 849 } 850 851const bool is_showing = !forceit && * cmd == NUL ; 852 853// Print header when showing autocommands. 854if (is_showing ) { 855// Highlight title 856msg_ext_set_kind ("list_cmd" ); 857msg_puts_title (_ ("\n--- Autocommands ---" )); 858 859if (* arg == '*' || * arg == '|' || * arg == NUL ) { 860au_show_for_all_events (group ,pat ); 861 }else { 862event_T event = event_name2nr (arg ,& arg ); 863assert (event < NUM_EVENTS ); 864au_show_for_event (group ,event ,pat ); 865 } 866 }else { 867if (* arg == '*' || * arg == NUL || * arg == '|' ) { 868if (* cmd != NUL ) { 869emsg (_ (e_cannot_define_autocommands_for_all_events )); 870 }else { 871do_all_autocmd_events (pat ,once ,nested ,cmd ,forceit ,group ); 872 } 873 }else { 874while (* arg && * arg != '|' && !ascii_iswhite (* arg )) { 875event_T event = event_name2nr (arg ,& arg ); 876assert (event < NUM_EVENTS ); 877if (do_autocmd_event (event ,pat ,once ,nested ,cmd ,forceit ,group )== FAIL ) { 878break ; 879 } 880 } 881 } 882 } 883 884err_exit : 885if (cmd_need_free ) { 886xfree (cmd ); 887 } 888xfree (envpat ); 889} 890 891void do_all_autocmd_events (const char * pat ,bool once ,int nested ,char * cmd ,bool del ,int group ) 892{ 893FOR_ALL_AUEVENTS (event ) { 894if (do_autocmd_event (event ,pat ,once ,nested ,cmd ,del ,group )== FAIL ) { 895return ; 896 } 897 } 898} 899 900// do_autocmd() for one event. 901// Defines an autocmd (does not execute; cf. apply_autocmds_group). 902// 903// If *pat == NUL: do for all patterns. 904// If *cmd == NUL: show entries. 905// If forceit == true: delete entries. 906// If group is not AUGROUP_ALL: only use this group. 907int do_autocmd_event (event_T event ,const char * pat ,bool once ,int nested ,const char * cmd , 908bool del ,int group ) 909FUNC_ATTR_NONNULL_ALL 910{ 911// Cannot be used to show all patterns. See au_show_for_event or au_show_for_all_events 912assert (* pat != NUL || del ); 913 914char buflocal_pat [BUFLOCAL_PAT_LEN ];// for "<buffer=X>" 915 916bool is_adding_cmd = * cmd != NUL ; 917const int findgroup = group == AUGROUP_ALL ?current_augroup :group ; 918 919// Delete all aupat for an event. 920if (* pat == NUL && del ) { 921aucmd_del_for_event_and_group (event ,findgroup ); 922return OK ; 923 } 924 925// Loop through all the specified patterns. 926int patlen = (int )aucmd_span_pattern (pat ,& pat ); 927while (patlen ) { 928const char * endpat = pat + patlen ; 929 930// detect special <buffer[=X]> buffer-local patterns 931bool is_buflocal = aupat_is_buflocal (pat ,patlen ); 932if (is_buflocal ) { 933const int buflocal_nr = aupat_get_buflocal_nr (pat ,patlen ); 934 935if (buflocal_nr == 0 || buflist_findnr (buflocal_nr )== NULL ) { 936semsg (_ (e_buffer_nr_invalid_buffer_number ),buflocal_nr ); 937return FAIL ; 938 } 939// normalize pat into standard "<buffer>#N" form 940aupat_normalize_buflocal_pat (buflocal_pat ,pat ,patlen ,buflocal_nr ); 941 942pat = buflocal_pat ; 943patlen = (int )strlen (buflocal_pat ); 944 } 945 946if (del ) { 947assert (* pat != NUL ); 948 949// Find existing autocommands with this pattern. 950AutoCmdVec * const acs = & autocmds [(int )event ]; 951for (size_t i = 0 ;i < kv_size (* acs );i ++ ) { 952AutoCmd * const ac = & kv_A (* acs ,i ); 953AutoPat * const ap = ac -> pat ; 954// Accept a pattern when: 955// - a group was specified and it's that group 956// - the length of the pattern matches 957// - the pattern matches. 958// For <buffer[=X]>, this condition works because we normalize 959// all buffer-local patterns. 960if (ap != NULL && ap -> group == findgroup && ap -> patlen == patlen 961&& strncmp (pat ,ap -> pat , (size_t )patlen )== 0 ) { 962// Remove existing autocommands. 963// If adding any new autocmd's for this AutoPat, don't 964// delete the pattern from the autopat list, append to 965// this list. 966aucmd_del (ac ); 967 } 968 } 969 } 970 971if (is_adding_cmd ) { 972Callback handler_fn = CALLBACK_INIT ; 973autocmd_register (0 ,event ,pat ,patlen ,group ,once ,nested ,NULL ,cmd ,& handler_fn ); 974 } 975 976patlen = (int )aucmd_span_pattern (endpat ,& pat ); 977 } 978 979au_cleanup ();// may really delete removed patterns/commands now 980return OK ; 981} 982 983/// Registers an autocmd. The handler may be a Ex command or callback function, decided by 984/// the `handler_cmd` or `handler_fn` args. 985/// 986/// @param handler_cmd Handler Ex command, or NULL if handler is a function (`handler_fn`). 987/// @param handler_fn Handler function, ignored if `handler_cmd` is not NULL. 988int autocmd_register (int64_t id ,event_T event ,const char * pat ,int patlen ,int group ,bool once , 989bool nested ,char * desc ,const char * handler_cmd ,Callback * handler_fn ) 990{ 991// 0 is not a valid group. 992assert (group != 0 ); 993 994if (patlen > (int )strlen (pat )) { 995return FAIL ; 996 } 997 998const int findgroup = group == AUGROUP_ALL ?current_augroup :group ; 999 1000// detect special <buffer[=X]> buffer-local patterns 1001const bool is_buflocal = aupat_is_buflocal (pat ,patlen ); 1002int buflocal_nr = 0 ; 1003 1004char buflocal_pat [BUFLOCAL_PAT_LEN ];// for "<buffer=X>" 1005if (is_buflocal ) { 1006buflocal_nr = aupat_get_buflocal_nr (pat ,patlen ); 1007 1008if (buflocal_nr == 0 || buflist_findnr (buflocal_nr )== NULL ) { 1009semsg (_ (e_buffer_nr_invalid_buffer_number ),buflocal_nr ); 1010return FAIL ; 1011 } 1012// normalize pat into standard "<buffer>#N" form 1013aupat_normalize_buflocal_pat (buflocal_pat ,pat ,patlen ,buflocal_nr ); 1014 1015pat = buflocal_pat ; 1016patlen = (int )strlen (buflocal_pat ); 1017 } 1018 1019// Try to reuse pattern from the last existing autocommand. 1020AutoPat * ap = NULL ; 1021AutoCmdVec * const acs = & autocmds [(int )event ]; 1022for (ptrdiff_t i = (ptrdiff_t )kv_size (* acs )- 1 ;i >=0 ;i -- ) { 1023ap = kv_A (* acs ,i ).pat ; 1024if (ap == NULL ) { 1025continue ;// Skip deleted autocommands. 1026 } 1027// Set result back to NULL if the last pattern doesn't match. 1028if (ap -> group != findgroup || ap -> patlen != patlen 1029|| strncmp (pat ,ap -> pat , (size_t )patlen )!= 0 ) { 1030ap = NULL ; 1031 } 1032break ; 1033 } 1034 1035// No matching pattern found, allocate a new one. 1036if (ap == NULL ) { 1037ap = xmalloc (sizeof (AutoPat )); 1038 1039if (is_buflocal ) { 1040ap -> buflocal_nr = buflocal_nr ; 1041ap -> reg_prog = NULL ; 1042 }else { 1043ap -> buflocal_nr = 0 ; 1044char * reg_pat = file_pat_to_reg_pat (pat ,pat + patlen ,& ap -> allow_dirs , true); 1045if (reg_pat != NULL ) { 1046// RE_NOBREAK: autocmd-pattern matching (aucmd_next()) must not os_breakcheck(). #35071 1047ap -> reg_prog = vim_regcomp (reg_pat ,RE_MAGIC |RE_NOBREAK ); 1048 } 1049xfree (reg_pat ); 1050if (reg_pat == NULL || ap -> reg_prog == NULL ) { 1051xfree (ap ); 1052return FAIL ; 1053 } 1054 } 1055 1056ap -> refcount = 0 ; 1057ap -> pat = xmemdupz (pat , (size_t )patlen ); 1058ap -> patlen = patlen ; 1059 1060// need to initialize last_mode for the first ModeChanged autocmd 1061if (event == EVENT_MODECHANGED && !has_event (EVENT_MODECHANGED )) { 1062get_mode (last_mode ); 1063 } 1064 1065// If the event is CursorMoved or CursorMovedI, update the last cursor position 1066// position to avoid immediately triggering the autocommand 1067if ((event == EVENT_CURSORMOVED && !has_event (EVENT_CURSORMOVED )) 1068|| (event == EVENT_CURSORMOVEDI && !has_event (EVENT_CURSORMOVEDI ))) { 1069last_cursormoved_win = curwin ; 1070last_cursormoved = curwin -> w_cursor ; 1071 } 1072 1073// Initialize the fields checked by the WinScrolled and 1074// WinResized trigger to prevent them from firing right after 1075// the first autocmd is defined. 1076if ((event == EVENT_WINSCROLLED || event == EVENT_WINRESIZED ) 1077&& !(has_event (EVENT_WINSCROLLED )|| has_event (EVENT_WINRESIZED ))) { 1078tabpage_T * save_curtab = curtab ; 1079FOR_ALL_TABS (tp ) { 1080unuse_tabpage (curtab ); 1081use_tabpage (tp ); 1082snapshot_windows_scroll_size (); 1083 } 1084unuse_tabpage (curtab ); 1085use_tabpage (save_curtab ); 1086 } 1087 1088ap -> group = group == AUGROUP_ALL ?current_augroup :group ; 1089 } 1090 1091ap -> refcount ++ ; 1092 1093// Add the autocmd at the end of the AutoCmd vector. 1094AutoCmd * ac = kv_pushp (autocmds [(int )event ]); 1095ac -> pat = ap ; 1096ac -> id = id ; 1097if (handler_cmd ) { 1098ac -> handler_cmd = xstrdup (handler_cmd ); 1099 }else { 1100ac -> handler_cmd = NULL ; 1101callback_copy (& ac -> handler_fn ,handler_fn ); 1102 } 1103ac -> script_ctx = current_sctx ; 1104ac -> script_ctx .sc_lnum += SOURCING_LNUM ; 1105nlua_set_sctx (& ac -> script_ctx ); 1106ac -> once = once ; 1107ac -> nested = nested ; 1108ac -> desc = desc == NULL ?NULL :xstrdup (desc ); 1109 1110return OK ; 1111} 1112 1113size_t aucmd_span_pattern (const char * pat ,const char ** start ) 1114FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 1115{ 1116// Skip leading commas. 1117while (* pat == ',' ) { 1118pat ++ ; 1119 } 1120 1121// Find end of the pattern. 1122// Watch out for a comma in braces, like "*.\{obj,o\}". 1123const char * p = pat ; 1124int brace_level = 0 ; 1125for (;* p && (* p != ',' || brace_level || (p > pat && p [-1 ]== '\\' ));p ++ ) { 1126if (* p == '{' ) { 1127brace_level ++ ; 1128 }else if (* p == '}' ) { 1129brace_level -- ; 1130 } 1131 } 1132 1133* start = pat ; 1134return (size_t )(p - pat ); 1135} 1136 1137/// Implementation of ":doautocmd [group] event [fname]". 1138/// Return OK for success, FAIL for failure; 1139/// 1140/// @param do_msg give message for no matching autocmds? 1141int do_doautocmd (char * arg_start ,bool do_msg ,bool * did_something ) 1142{ 1143char * arg = arg_start ; 1144int nothing_done = true; 1145 1146if (did_something != NULL ) { 1147* did_something = false; 1148 } 1149 1150// Check for a legal group name. If not, use AUGROUP_ALL. 1151int group = arg_augroup_get (& arg ); 1152 1153if (* arg == '*' ) { 1154emsg (_ ("E217: Can't execute autocommands for ALL events" )); 1155return FAIL ; 1156 } 1157 1158// Scan over the events. 1159// If we find an illegal name, return here, don't do anything. 1160char * fname = arg_event_skip (arg ,group != AUGROUP_ALL ); 1161if (fname == NULL ) { 1162return FAIL ; 1163 } 1164 1165fname = skipwhite (fname ); 1166 1167// Loop over the events. 1168while (* arg && !ends_excmd (* arg )&& !ascii_iswhite (* arg )) { 1169if (apply_autocmds_group (event_name2nr (arg ,& arg ),fname ,NULL , true,group , 1170curbuf ,curwin ,NULL ,NULL , false)) { 1171nothing_done = false; 1172 } 1173 } 1174 1175if (nothing_done && do_msg && !aborting ()) { 1176smsg (0 ,_ ("No matching autocommands: %s" ),arg_start ); 1177 } 1178if (did_something != NULL ) { 1179* did_something = !nothing_done ; 1180 } 1181 1182return aborting () ?FAIL :OK ; 1183} 1184 1185// ":doautoall": execute autocommands for each loaded buffer. 1186void ex_doautoall (exarg_T * eap ) 1187{ 1188int retval = OK ; 1189CtxSwitch aco = {0 }; 1190char * arg = eap -> arg ; 1191int call_do_modelines = check_nomodeline (& arg ); 1192bufref_T bufref ; 1193bool did_aucmd ; 1194 1195// This is a bit tricky: For some commands curwin->w_buffer needs to be 1196// equal to curbuf, but for some buffers there may not be a window. 1197// So we change the buffer for the current window for a moment. This 1198// gives problems when the autocommands make changes to the list of 1199// buffers or windows... 1200FOR_ALL_BUFFERS (buf ) { 1201// Only do loaded buffers and skip the current buffer, it's done last. 1202if (buf -> b_ml .ml_mfp == NULL || buf == curbuf ) { 1203continue ; 1204 } 1205 1206// Find a window for this buffer and save some values. 1207ctx_switch (& aco ,NULL ,NULL ,buf ,0 ); 1208set_bufref (& bufref ,buf ); 1209 1210// execute the autocommands for this buffer 1211retval = do_doautocmd (arg , false,& did_aucmd ); 1212 1213if (call_do_modelines && did_aucmd ) { 1214// Execute the modeline settings, but don't set window-local 1215// options if we are using the current window for another 1216// buffer. 1217do_modelines (is_ctx_win (curwin ) ?OPT_NOWIN :0 ); 1218 } 1219 1220// restore the current window 1221ctx_restore (& aco ); 1222 1223// Stop if there is some error or buffer was deleted. 1224if (retval == FAIL || !bufref_valid (& bufref )) { 1225retval = FAIL ; 1226break ; 1227 } 1228 } 1229 1230// Execute autocommands for the current buffer last. 1231if (retval == OK ) { 1232do_doautocmd (arg , false,& did_aucmd ); 1233if (call_do_modelines && did_aucmd ) { 1234do_modelines (0 ); 1235 } 1236 } 1237} 1238 1239/// Check *argp for <nomodeline>. When it is present return false, otherwise 1240/// return true and advance *argp to after it. Thus do_modelines() should be 1241/// called when true is returned. 1242/// 1243/// @param[in,out] argp argument string 1244bool check_nomodeline (char ** argp ) 1245FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 1246{ 1247if (strncmp (* argp ,"<nomodeline>" ,12 )== 0 ) { 1248* argp = skipwhite (* argp + 12 ); 1249return false; 1250 } 1251return true; 1252} 1253 1254/// Schedules an autocommand event, to be executed at the next event-loop tick. 1255/// 1256/// @param event Event to schedule 1257/// @param fname Name to use as `<amatch>` (the "pattern"). NULL/empty means use actual filename. 1258/// @param fname_io Filename to use for <afile> on cmdline, NULL means use `fname`. 1259/// @param group Group ID or AUGROUP_ALL 1260/// @param buf Buffer for <abuf> 1261/// @param eap Ex command arguments 1262/// @param data Event-specific data. Will be copied, caller must free `data`. 1263/// The `data` items will also be copied to `v:event`. 1264void aucmd_defer (event_T event ,char * fname ,char * fname_io ,int group ,buf_T * buf ,exarg_T * eap , 1265Object * data ) 1266{ 1267AutoCmdEvent * evdata = xmalloc (sizeof (AutoCmdEvent )); 1268evdata -> event = event ; 1269evdata -> fname = fname != NULL ?xstrdup (fname ) :NULL ; 1270evdata -> fname_io = fname_io != NULL ?xstrdup (fname_io ) :NULL ; 1271evdata -> group = group ; 1272evdata -> buf = buf -> handle ; 1273evdata -> eap = eap ; 1274if (data ) { 1275evdata -> data = xmalloc (sizeof (Object )); 1276* evdata -> data = copy_object (* data ,NULL ); 1277 }else { 1278evdata -> data = NULL ; 1279 } 1280 1281multiqueue_put (deferred_events ,deferred_event ,evdata ); 1282} 1283 1284/// Executes a deferred autocommand event. 1285static void deferred_event (void ** argv ) 1286{ 1287AutoCmdEvent * e = argv [0 ]; 1288event_T event = e -> event ; 1289char * fname = e -> fname ; 1290char * fname_io = e -> fname_io ; 1291int group = e -> group ; 1292exarg_T * eap = e -> eap ; 1293Object * data = e -> data ; 1294 1295Error err = ERROR_INIT ; 1296buf_T * buf = find_buffer_by_handle (e -> buf ,& err ); 1297if (buf ) { 1298// Copy `data` to `v:event`. 1299save_v_event_T save_v_event ; 1300dict_T * v_event = get_v_event (& save_v_event ); 1301if (data && data -> type == kObjectTypeDict ) { 1302for (size_t i = 0 ;i < data -> data .dict .size ;i ++ ) { 1303KeyValuePair item = data -> data .dict .items [i ]; 1304typval_T tv ; 1305object_to_vim (item .value ,& tv ,& err ); 1306if (ERROR_SET (& err )) { 1307api_clear_error (& err ); 1308continue ; 1309 } 1310tv_dict_add_tv (v_event ,item .key .data ,item .key .size ,& tv ); 1311tv_clear (& tv ); 1312 } 1313 } 1314tv_dict_set_keys_readonly (v_event ); 1315 1316win_T * win = curwin ;// before ctx_switch() may make the context window current 1317 1318CtxSwitch aco = {0 }; 1319ctx_switch (& aco ,NULL ,NULL ,buf ,0 ); 1320apply_autocmds_group (event ,fname ,fname_io , false,group ,buf ,win ,eap ,data , false); 1321ctx_restore (& aco ); 1322 1323restore_v_event (v_event ,& save_v_event ); 1324 } 1325 1326xfree (fname ); 1327xfree (fname_io ); 1328if (data ) { 1329api_free_object (* data ); 1330xfree (data ); 1331 } 1332xfree (e ); 1333} 1334 1335static void deferred_optionset_modified (void ** argv ) 1336{ 1337Error err = ERROR_INIT ; 1338buf_T * buf = find_buffer_by_handle ((handle_T )(uintptr_t )argv [0 ],& err ); 1339api_clear_error (& err ); 1340if (buf ) { 1341bool new_val = (bool )(uintptr_t )argv [1 ]; 1342Object old = BOOLEAN_OBJ (!new_val ); 1343Object new = BOOLEAN_OBJ (new_val ); 1344CtxSwitch aco = {0 }; 1345ctx_switch (& aco ,NULL ,NULL ,buf ,0 ); 1346apply_optionset_autocmd_now (kOptModified ,OPT_LOCAL ,old ,old ,old ,new ); 1347ctx_restore (& aco ); 1348 } 1349} 1350 1351/// Special case of aucmd_defer for `OptionSet modified`. 1352void aucmd_defer_modified (buf_T * buf ,bool new_val ) 1353{ 1354if (!has_event (EVENT_OPTIONSET ) 1355|| (bt_nofile (buf )&& !buf -> b_p_bl ) 1356|| * get_vim_var_str (VV_OPTION_TYPE )!= NUL ) { 1357return ; 1358 } 1359multiqueue_put (deferred_events ,deferred_optionset_modified , 1360 (void * )(uintptr_t )buf -> handle , 1361 (void * )(uintptr_t )new_val ); 1362} 1363 1364/// Execute autocommands for "event" and file name "fname". 1365/// 1366/// `ev.win` is curwin; use apply_autocmds_win() for window-specific events. 1367/// 1368/// @param event event that occurred 1369/// @param fname filename, NULL or empty means use actual file name 1370/// @param fname_io filename to use for <afile> on cmdline 1371/// @param force Ignore autocmd_busy (force "++nested" behavior) 1372/// @param buf Buffer for <abuf> 1373/// 1374/// @return true if some commands were executed. 1375bool apply_autocmds (event_T event ,char * fname ,char * fname_io ,bool force ,buf_T * buf ) 1376{ 1377return apply_autocmds_group (event ,fname ,fname_io ,force ,AUGROUP_ALL ,buf ,curwin ,NULL ,NULL , 1378 false); 1379} 1380 1381/// Like apply_autocmds(), but with an explicit window for `ev.win`. 1382/// 1383/// @param win Window for `ev.win`, NULL for the current window. 1384/// 1385/// @return true if some commands were executed. 1386bool apply_autocmds_win (event_T event ,char * fname ,char * fname_io ,bool force ,buf_T * buf , 1387win_T * win ) 1388{ 1389return apply_autocmds_group (event ,fname ,fname_io ,force ,AUGROUP_ALL ,buf ,win ,NULL ,NULL , 1390 false); 1391} 1392 1393/// Like apply_autocmds(), but with extra "eap" argument. This takes care of 1394/// setting v:filearg. 1395/// 1396/// @param event event that occurred 1397/// @param fname NULL or empty means use actual file name 1398/// @param fname_io fname to use for <afile> on cmdline 1399/// @param force Ignore autocmd_busy (force "++nested" behavior) 1400/// @param buf Buffer for <abuf> 1401/// @param exarg Ex command arguments 1402/// 1403/// @return true if some commands were executed. 1404bool apply_autocmds_exarg (event_T event ,char * fname ,char * fname_io ,bool force ,buf_T * buf , 1405exarg_T * eap ) 1406{ 1407return apply_autocmds_group (event ,fname ,fname_io ,force ,AUGROUP_ALL ,buf ,curwin ,eap ,NULL , 1408 false); 1409} 1410 1411/// Like apply_autocmds(), but handles the caller's retval. If the script 1412/// processing is being aborted or if retval is FAIL when inside a try 1413/// conditional, no autocommands are executed. If otherwise the autocommands 1414/// cause the script to be aborted, retval is set to FAIL. 1415/// 1416/// @param event event that occurred 1417/// @param fname NULL or empty means use actual file name 1418/// @param fname_io fname to use for <afile> on cmdline 1419/// @param force Ignore autocmd_busy (force "++nested" behavior) 1420/// @param buf Buffer for <abuf> 1421/// @param[in,out] retval caller's retval 1422/// 1423/// @return true if some autocommands were executed 1424bool apply_autocmds_retval (event_T event ,char * fname ,char * fname_io ,bool force ,buf_T * buf , 1425int * retval ) 1426{ 1427if (should_abort (* retval )) { 1428return false; 1429 } 1430 1431bool did_cmd = apply_autocmds_group (event ,fname ,fname_io ,force ,AUGROUP_ALL ,buf ,curwin ,NULL , 1432NULL , false); 1433if (did_cmd && aborting ()) { 1434* retval = FAIL ; 1435 } 1436return did_cmd ; 1437} 1438 1439/// Return true if "event" autocommand is defined. 1440/// 1441/// @param event the autocommand to check 1442bool has_event (event_T event )FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 1443{ 1444return kv_size (autocmds [(int )event ])!= 0 ; 1445} 1446 1447/// Return true when there is a CursorHold/CursorHoldI autocommand defined for 1448/// the current mode. 1449static bool has_cursorhold (void )FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 1450{ 1451return has_event ((get_real_state ()== MODE_NORMAL_BUSY ?EVENT_CURSORHOLD :EVENT_CURSORHOLDI )); 1452} 1453 1454/// Return true if the CursorHold/CursorHoldI event can be triggered. 1455bool trigger_cursorhold (void )FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 1456{ 1457if (!did_cursorhold && has_cursorhold ()&& reg_recording == 0 1458&& typebuf .tb_len == 0 && !ins_compl_active ()) { 1459int state = get_real_state (); 1460if (state == MODE_NORMAL_BUSY || (state & MODE_INSERT )!= 0 ) { 1461return true; 1462 } 1463 } 1464return false; 1465} 1466 1467/// Execute autocommands for "event" and file name "fname". 1468/// 1469/// @param event event that occurred 1470/// @param fname filename, NULL or empty means use actual file name 1471/// @param fname_io filename to use for <afile> on cmdline, 1472/// NULL means use `fname`. 1473/// @param force Ignore autocmd_busy (force "++nested" behavior) 1474/// @param group autocmd group ID or AUGROUP_ALL 1475/// @param buf Buffer for <abuf> 1476/// @param win Window for `ev.win`, NULL for the current window. 1477/// @param eap Ex command arguments 1478/// @param with_buf Run callbacks with "buf" as the current buffer 1479/// 1480/// @return true if some commands were executed. 1481bool apply_autocmds_group (event_T event ,char * fname ,char * fname_io ,bool force ,int group , 1482buf_T * buf ,win_T * win ,exarg_T * eap ,Object * data ,bool with_buf ) 1483{ 1484char * sfname = NULL ;// short file name 1485bool retval = false; 1486static int nesting = 0 ; 1487char * save_cmdarg ; 1488static bool filechangeshell_busy = false; 1489proftime_T wait_time ; 1490bool did_save_redobuff = false; 1491RedoState save_redo ; 1492const bool save_KeyTyped = KeyTyped ; 1493ESTACK_CHECK_DECLARATION ; 1494CtxSwitch aco = {0 }; 1495bool save_changed = false; 1496buf_T * old_curbuf = NULL ; 1497 1498// Quickly return if there are no autocommands for this event or 1499// autocommands are blocked. 1500if (event == NUM_EVENTS || kv_size (autocmds [(int )event ])== 0 || is_autocmd_blocked ()) { 1501 gotoBYPASS_AU ; 1502 } 1503 1504// When autocommands are busy, new autocommands are only executed when 1505// explicitly enabled with the "nested" flag. 1506if (autocmd_busy && !(force || autocmd_nested )) { 1507 gotoBYPASS_AU ; 1508 } 1509 1510// Quickly return when immediately aborting on error, or when an interrupt 1511// occurred or an exception was thrown but not caught. 1512if (aborting ()) { 1513 gotoBYPASS_AU ; 1514 } 1515 1516// FileChangedShell never nests, because it can create an endless loop. 1517if (filechangeshell_busy 1518&& (event == EVENT_FILECHANGEDSHELL || event == EVENT_FILECHANGEDSHELLPOST )) { 1519 gotoBYPASS_AU ; 1520 } 1521 1522// Ignore events in 'eventignore'. 1523if (event_ignored (event ,p_ei )) { 1524 gotoBYPASS_AU ; 1525 } 1526 1527bool win_ignore = false; 1528// If event is allowed in 'eventignorewin', check if curwin or all windows 1529// into "buf" are ignoring the event. 1530if (buf == curbuf && event_names [event ].event <=0 ) { 1531win_ignore = event_ignored (event ,curwin -> w_p_eiw ); 1532 }else if (buf != NULL && event_names [event ].event <=0 && buf -> b_nwindows > 0 ) { 1533win_ignore = true; 1534FOR_ALL_TAB_WINDOWS (tp ,wp ) { 1535if (wp -> w_buffer == buf && !event_ignored (event ,wp -> w_p_eiw )) { 1536win_ignore = false; 1537break ; 1538 } 1539 } 1540 } 1541if (win_ignore ) { 1542 gotoBYPASS_AU ; 1543 } 1544 1545// Allow nesting of autocommands, but restrict the depth, because it's 1546// possible to create an endless loop. 1547if (nesting == 10 ) { 1548emsg (_ (e_autocommand_nesting_too_deep )); 1549 gotoBYPASS_AU ; 1550 } 1551 1552// Check if these autocommands are disabled. Used when doing ":all" or 1553// ":ball". 1554if ((autocmd_no_enter && (event == EVENT_WINENTER || event == EVENT_BUFENTER )) 1555|| (autocmd_no_leave && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE ))) { 1556 gotoBYPASS_AU ; 1557 } 1558 1559// Save the autocmd_* variables and info about the current buffer. 1560char * save_autocmd_fname = autocmd_fname ; 1561bool save_autocmd_fname_full = autocmd_fname_full ; 1562int save_autocmd_bufnr = autocmd_bufnr ; 1563handle_T save_autocmd_winid = autocmd_winid ; 1564char * save_autocmd_match = autocmd_match ; 1565int save_autocmd_busy = autocmd_busy ; 1566int save_autocmd_nested = autocmd_nested ; 1567// Set the file name to be used for <afile>. 1568// Make a copy to avoid that changing a buffer name or directory makes it 1569// invalid. 1570if (fname_io == NULL ) { 1571if (event == EVENT_COLORSCHEME || event == EVENT_COLORSCHEMEPRE 1572|| event == EVENT_OPTIONSET || event == EVENT_MODECHANGED 1573|| event == EVENT_MARKSET ) { 1574autocmd_fname = NULL ; 1575 }else if (fname != NULL && !ends_excmd (* fname )) { 1576autocmd_fname = fname ; 1577 }else if (buf != NULL ) { 1578autocmd_fname = buf -> b_ffname ; 1579 }else { 1580autocmd_fname = NULL ; 1581 } 1582 }else { 1583autocmd_fname = fname_io ; 1584 } 1585char * afile_orig = NULL ;///< Unexpanded <afile> 1586if (autocmd_fname != NULL ) { 1587afile_orig = xstrdup (autocmd_fname ); 1588// Allocate MAXPATHL for when eval_vars() resolves the fullpath. 1589autocmd_fname = xstrnsave (autocmd_fname ,MAXPATHL ); 1590 } 1591autocmd_fname_full = false;// call FullName_save() later 1592 1593// Set the buffer number to be used for <abuf>. 1594autocmd_bufnr = buf == NULL ?0 :buf -> b_fnum ; 1595 1596// When the file name is NULL or empty, use the file name of buffer "buf". 1597// Always use the full path of the file name to match with, in case 1598// "allow_dirs" is set. 1599if (fname == NULL || * fname == NUL ) { 1600if (buf == NULL ) { 1601fname = NULL ; 1602 }else { 1603if (event == EVENT_SYNTAX ) { 1604fname = buf -> b_p_syn ; 1605 }else if (event == EVENT_FILETYPE ) { 1606fname = buf -> b_p_ft ; 1607 }else { 1608if (buf -> b_sfname != NULL ) { 1609sfname = xstrdup (buf -> b_sfname ); 1610 } 1611fname = buf -> b_ffname ; 1612 } 1613 } 1614if (fname == NULL ) { 1615fname = "" ; 1616 } 1617fname = xstrdup (fname );// make a copy, so we can change it 1618 }else { 1619sfname = TO_SLASH_SAVE (fname ); 1620// Don't try expanding the following events. 1621if (event == EVENT_CMDATOM 1622|| event == EVENT_CMDLINECHANGED 1623|| event == EVENT_CMDLINEENTER 1624|| event == EVENT_CMDLINELEAVEPRE 1625|| event == EVENT_CMDLINELEAVE 1626|| event == EVENT_CMDUNDEFINED 1627|| event == EVENT_CURSORMOVEDC 1628|| event == EVENT_CMDWINENTER 1629|| event == EVENT_CMDWINLEAVE 1630|| event == EVENT_COLORSCHEME 1631|| event == EVENT_COLORSCHEMEPRE 1632|| event == EVENT_DIRCHANGED 1633|| event == EVENT_DIRCHANGEDPRE 1634|| event == EVENT_FILETYPE 1635|| event == EVENT_FUNCUNDEFINED 1636|| event == EVENT_MARKSET 1637|| event == EVENT_MENUPOPUP 1638|| event == EVENT_MODECHANGED 1639|| event == EVENT_OPTIONSET 1640|| event == EVENT_PROGRESS 1641|| event == EVENT_QUICKFIXCMDPOST 1642|| event == EVENT_QUICKFIXCMDPRE 1643|| event == EVENT_REMOTEREPLY 1644|| event == EVENT_SIGNAL 1645|| event == EVENT_SPELLFILEMISSING 1646|| event == EVENT_SYNTAX 1647|| event == EVENT_TABCLOSED 1648|| event == EVENT_TABMOVED 1649|| event == EVENT_USER 1650|| event == EVENT_WINCLOSED 1651|| event == EVENT_WINRESIZED 1652|| event == EVENT_WINSCROLLED ) { 1653fname = TO_SLASH_SAVE (fname ); 1654autocmd_fname_full = true;// don't expand it later 1655 }else { 1656fname = FullName_save (fname , false); 1657 } 1658 } 1659if (fname == NULL ) {// out of memory 1660xfree (sfname ); 1661retval = false; 1662 gotoBYPASS_AU ; 1663 } 1664 1665// Set the window handle for `ev.win`. After the last "goto BYPASS_AU", which 1666// skips the restore below, and before ctx_switch(). 1667autocmd_winid = win != NULL ?win -> handle : (curwin != NULL ?curwin -> handle :0 ); 1668 1669if (with_buf && buf != NULL && buf != curbuf ) { 1670ctx_switch (& aco ,NULL ,NULL ,buf ,0 ); 1671 } 1672 1673save_changed = curbuf -> b_changed ; 1674old_curbuf = curbuf ; 1675 1676// Set the name to be used for <amatch>. 1677autocmd_match = fname ; 1678 1679// Don't redraw while doing autocommands. 1680RedrawingDisabled ++ ; 1681 1682// name and lnum are filled in later 1683estack_push (ETYPE_AUCMD ,NULL ,0 ); 1684ESTACK_CHECK_SETUP ; 1685 1686const sctx_T save_current_sctx = current_sctx ; 1687 1688if (do_profiling == PROF_YES ) { 1689prof_child_enter (& wait_time );// doesn't count for the caller itself 1690 } 1691 1692// Don't use local function variables, if called from a function. 1693funccal_entry_T funccal_entry ; 1694save_funccal (& funccal_entry ); 1695 1696// When starting to execute autocommands, save the search patterns. 1697if (!autocmd_busy ) { 1698save_search_patterns (); 1699if (!ins_compl_active ()) { 1700save_redobuff (& save_redo ); 1701did_save_redobuff = true; 1702 } 1703curbuf -> b_did_filetype = curbuf -> b_keep_filetype ; 1704 } 1705 1706// Note that we are applying autocmds. Some commands need to know. 1707autocmd_busy = true; 1708filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL ); 1709nesting ++ ;// see matching decrement below 1710 1711// Remember that FileType was triggered, if 'filetype' was actually set. For :setf. 1712if (event == EVENT_FILETYPE && * curbuf -> b_p_ft != NUL ) { 1713curbuf -> b_did_filetype = true; 1714 } 1715 1716char * tail = path_tail (fname ); 1717 1718// Find first autocommand that matches 1719AutoPatCmd patcmd = { 1720// aucmd_next will set lastpat back to NULL if there are no more autocommands left to run 1721 .lastpat = NULL , 1722// current autocommand index 1723 .auidx = 0 , 1724// save vector size, to avoid an endless loop when more patterns 1725// are added when executing autocommands 1726 .ausize = kv_size (autocmds [(int )event ]), 1727 .afile_orig = afile_orig , 1728 .fname = fname , 1729 .sfname = sfname , 1730 .tail = tail , 1731 .group = group , 1732 .event = event , 1733 .arg_bufnr = autocmd_bufnr , 1734 }; 1735aucmd_next (& patcmd ); 1736 1737// Found first autocommand, start executing them 1738if (patcmd .lastpat != NULL ) { 1739// add to active_apc_list 1740patcmd .next = active_apc_list ; 1741active_apc_list = & patcmd ; 1742 1743// Attach data to command 1744patcmd .data = data ; 1745 1746// set v:cmdarg (only when there is a matching pattern) 1747varnumber_T save_cmdbang = get_vim_var_nr (VV_CMDBANG ); 1748if (eap != NULL ) { 1749save_cmdarg = set_cmdarg (eap ,NULL ); 1750set_vim_var_nr (VV_CMDBANG ,eap -> forceit ); 1751 }else { 1752save_cmdarg = NULL ;// avoid gcc warning 1753 } 1754retval = true; 1755 1756// Make sure cursor and topline are valid. The first time the current 1757// values are saved, restored by reset_lnums(). When nested only the 1758// values are corrected when needed. 1759if (nesting == 1 ) { 1760check_lnums (true); 1761 }else { 1762check_lnums_nested (true); 1763 } 1764 1765const int save_did_emsg = did_emsg ; 1766 1767// Execute the autocmd. The `getnextac` callback handles iteration. 1768do_cmdline (NULL ,getnextac ,& patcmd ,DOCMD_NOWAIT |DOCMD_VERBOSE |DOCMD_REPEAT ); 1769 1770did_emsg += save_did_emsg ; 1771 1772if (nesting == 1 ) { 1773// restore cursor and topline, unless they were changed 1774reset_lnums (); 1775 } 1776 1777if (eap != NULL ) { 1778set_cmdarg (NULL ,save_cmdarg ); 1779set_vim_var_nr (VV_CMDBANG ,save_cmdbang ); 1780 } 1781// delete from active_apc_list 1782if (active_apc_list == & patcmd ) {// just in case 1783active_apc_list = patcmd .next ; 1784 } 1785 } 1786 1787RedrawingDisabled -- ; 1788autocmd_busy = save_autocmd_busy ; 1789filechangeshell_busy = false; 1790autocmd_nested = save_autocmd_nested ; 1791xfree (SOURCING_NAME ); 1792ESTACK_CHECK_NOW ; 1793estack_pop (); 1794xfree (afile_orig ); 1795xfree (autocmd_fname ); 1796autocmd_fname = save_autocmd_fname ; 1797autocmd_fname_full = save_autocmd_fname_full ; 1798autocmd_bufnr = save_autocmd_bufnr ; 1799autocmd_winid = save_autocmd_winid ; 1800autocmd_match = save_autocmd_match ; 1801current_sctx = save_current_sctx ; 1802restore_funccal (); 1803if (do_profiling == PROF_YES ) { 1804prof_child_exit (& wait_time ); 1805 } 1806KeyTyped = save_KeyTyped ; 1807xfree (fname ); 1808xfree (sfname ); 1809nesting -- ;// see matching increment above 1810 1811// When stopping to execute autocommands, restore the search patterns and 1812// the redo buffer. Free any buffers in the au_pending_free_buf list and 1813// free any windows in the au_pending_free_win list. 1814if (!autocmd_busy ) { 1815restore_search_patterns (); 1816if (did_save_redobuff ) { 1817restore_redobuff (& save_redo ); 1818 } 1819curbuf -> b_did_filetype = false; 1820while (au_pending_free_buf != NULL ) { 1821buf_T * b = au_pending_free_buf -> b_next ; 1822 1823xfree (au_pending_free_buf ); 1824au_pending_free_buf = b ; 1825 } 1826while (au_pending_free_win != NULL ) { 1827win_T * w = au_pending_free_win -> w_next ; 1828 1829xfree (au_pending_free_win ); 1830au_pending_free_win = w ; 1831 } 1832 } 1833 1834// Some events don't set or reset the Changed flag. 1835// Check if still in the same buffer! 1836if (curbuf == old_curbuf 1837&& (event == EVENT_BUFREADPOST || event == EVENT_BUFWRITEPOST 1838|| event == EVENT_FILEAPPENDPOST || event == EVENT_VIMLEAVE 1839|| event == EVENT_VIMLEAVEPRE )) { 1840if (curbuf -> b_changed != save_changed ) { 1841need_maketitle = true; 1842 } 1843curbuf -> b_changed = save_changed ; 1844 } 1845 1846au_cleanup ();// may really delete removed patterns/commands now 1847 1848BYPASS_AU : 1849// When wiping out a buffer make sure all its buffer-local autocommands 1850// are deleted. 1851if (event == EVENT_BUFWIPEOUT && buf != NULL ) { 1852aubuflocal_remove (buf ); 1853 } 1854 1855if (retval == OK && event == EVENT_FILETYPE ) { 1856curbuf -> b_au_did_filetype = true; 1857 } 1858 1859ctx_restore (& aco ); 1860 1861return retval ; 1862} 1863 1864void do_termresponse_autocmd (const String sequence ,uint64_t channel_id ) 1865{ 1866MAXSIZE_TEMP_DICT (data ,2 ); 1867PUT_C (data ,"sequence" ,STRING_OBJ (sequence )); 1868PUT_C (data ,"chan" ,INTEGER_OBJ ((Integer )channel_id )); 1869apply_autocmds_group (EVENT_TERMRESPONSE ,NULL ,NULL , true,AUGROUP_ALL ,NULL ,curwin ,NULL , 1870& DICT_OBJ (data ), false); 1871termresponse_changed = true; 1872termresponse_chan_id = channel_id ; 1873} 1874 1875// Block triggering autocommands until unblock_autocmd() is called. 1876// Can be used recursively, so long as it's symmetric. 1877void block_autocmds (void ) 1878{ 1879// Detect if v:termresponse is set while blocked. 1880if (!is_autocmd_blocked ()) { 1881termresponse_changed = false; 1882termresponse_chan_id = 0 ; 1883 } 1884autocmd_blocked ++ ; 1885} 1886 1887void unblock_autocmds (void ) 1888{ 1889autocmd_blocked -- ; 1890 1891// When v:termresponse was set while autocommands were blocked, trigger 1892// the autocommands now. Esp. useful when executing a shell command 1893// during startup (nvim -d). 1894if (!is_autocmd_blocked ()&& termresponse_changed && has_event (EVENT_TERMRESPONSE )) { 1895// Copied to a new allocation, as termresponse may be freed during the event. 1896const String sequence = cstr_to_string (get_vim_var_str (VV_TERMRESPONSE )); 1897do_termresponse_autocmd (sequence ,termresponse_chan_id ); 1898api_free_string (sequence ); 1899 } 1900} 1901 1902bool is_autocmd_blocked (void ) 1903FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 1904{ 1905return autocmd_blocked != 0 ; 1906} 1907 1908/// Find next matching autocommand. 1909/// If next autocommand was not found, sets lastpat to NULL and cmdidx to SIZE_MAX on apc. 1910static void aucmd_next (AutoPatCmd * apc ) 1911{ 1912estack_T * const entry = ((estack_T * )exestack .ga_data )+ exestack .ga_len - 1 ; 1913 1914AutoCmdVec * const acs = & autocmds [(int )apc -> event ]; 1915assert (apc -> ausize <=kv_size (* acs )); 1916for (size_t i = apc -> auidx ;i < apc -> ausize && !got_int ;i ++ ) { 1917AutoCmd * const ac = & kv_A (* acs ,i ); 1918AutoPat * const ap = ac -> pat ; 1919 1920// Skip deleted autocommands. 1921if (ap == NULL ) { 1922continue ; 1923 } 1924// Skip matching if pattern didn't change. 1925if (ap != apc -> lastpat ) { 1926// Skip autocommands that don't match the group. 1927if (apc -> group != AUGROUP_ALL && apc -> group != ap -> group ) { 1928continue ; 1929 } 1930// Skip autocommands that don't match the pattern or buffer number. 1931if (ap -> buflocal_nr == 0 1932 ? !match_file_pat (NULL ,& ap -> reg_prog ,apc -> fname ,apc -> sfname ,apc -> tail ,ap -> allow_dirs ) 1933 :ap -> buflocal_nr != apc -> arg_bufnr ) { 1934continue ; 1935 } 1936 1937const char * const name = event_nr2name (apc -> event ); 1938const char * const s = _ ("%s Autocommands for \"%s\"" ); 1939 1940const size_t sourcing_name_len = strlen (s )+ strlen (name )+ (size_t )ap -> patlen + 1 ; 1941char * const namep = xmalloc (sourcing_name_len ); 1942snprintf (namep ,sourcing_name_len ,s ,name ,ap -> pat ); 1943if (p_verbose >=8 ) { 1944verbose_enter (); 1945smsg (0 ,_ ("Executing %s" ),namep ); 1946verbose_leave (); 1947 } 1948 1949// Update the exestack entry for this autocmd. 1950XFREE_CLEAR (entry -> es_name ); 1951entry -> es_name = namep ; 1952entry -> es_info .aucmd = apc ; 1953 } 1954 1955apc -> lastpat = ap ; 1956apc -> auidx = i ; 1957 1958line_breakcheck (); 1959return ; 1960 } 1961 1962// Clear the exestack entry for this ETYPE_AUCMD entry. 1963XFREE_CLEAR (entry -> es_name ); 1964entry -> es_info .aucmd = NULL ; 1965 1966apc -> lastpat = NULL ; 1967apc -> auidx = SIZE_MAX ; 1968} 1969 1970/// Executes an autocmd callback function (as opposed to an Ex command). 1971static bool au_callback (const AutoCmd * ac ,const AutoPatCmd * apc ) 1972{ 1973Callback callback = ac -> handler_fn ; 1974if (callback .type == kCallbackLua ) { 1975MAXSIZE_TEMP_DICT (data ,8 ); 1976PUT_C (data ,"id" ,INTEGER_OBJ (ac -> id )); 1977PUT_C (data ,"event" ,CSTR_AS_OBJ (event_nr2name (apc -> event ))); 1978PUT_C (data ,"file" ,CSTR_AS_OBJ (apc -> afile_orig )); 1979PUT_C (data ,"match" ,CSTR_AS_OBJ (autocmd_match )); 1980PUT_C (data ,"buf" ,INTEGER_OBJ (autocmd_bufnr )); 1981PUT_C (data ,"win" ,INTEGER_OBJ (autocmd_winid )); 1982 1983if (apc -> data ) { 1984PUT_C (data ,"data" ,* apc -> data ); 1985 } 1986 1987int group = ac -> pat -> group ; 1988switch (group ) { 1989case AUGROUP_ERROR : 1990abort ();// unreachable 1991case AUGROUP_DEFAULT : 1992case AUGROUP_ALL : 1993case AUGROUP_DELETED : 1994// omit group in these cases 1995break ; 1996default : 1997PUT_C (data ,"group" ,INTEGER_OBJ (group )); 1998break ; 1999 } 2000 2001MAXSIZE_TEMP_ARRAY (args ,1 ); 2002ADD_C (args ,DICT_OBJ (data )); 2003 2004Object result = nlua_call_ref (callback .data .luaref ,NULL ,args ,kRetNilBool ,NULL ,NULL ); 2005return LUARET_TRUTHY (result ); 2006 }else { 2007typval_T argsin = TV_INITIAL_VALUE ; 2008typval_T rettv = TV_INITIAL_VALUE ; 2009callback_call (& callback ,0 ,& argsin ,& rettv ); 2010return false; 2011 } 2012} 2013 2014/// Get next autocommand command. 2015/// Called by do_cmdline() to get the next line for ":if". 2016/// @return allocated string, or NULL for end of autocommands. 2017char * getnextac (int c ,void * cookie ,int indent ,bool do_concat ) 2018{ 2019// These arguments are required for do_cmdline. 2020 (void )c ; 2021 (void )indent ; 2022 (void )do_concat ; 2023 2024AutoPatCmd * const apc = (AutoPatCmd * )cookie ; 2025AutoCmdVec * const acs = & autocmds [(int )apc -> event ]; 2026 2027aucmd_next (apc ); 2028if (apc -> lastpat == NULL ) { 2029return NULL ; 2030 } 2031 2032assert (apc -> auidx < kv_size (* acs )); 2033AutoCmd * const ac = & kv_A (* acs ,apc -> auidx ); 2034assert (ac -> pat != NULL ); 2035bool oneshot = ac -> once ; 2036 2037if (p_verbose >=9 ) { 2038verbose_enter_scroll (); 2039char * handler_str = aucmd_handler_to_string (ac ); 2040smsg (0 ,_ ("autocommand %s" ),handler_str ); 2041msg_puts ("\n" );// don't overwrite this either 2042XFREE_CLEAR (handler_str ); 2043verbose_leave_scroll (); 2044 } 2045 2046// Make sure to set autocmd_nested before executing 2047// lua code, so that it works properly 2048autocmd_nested = ac -> nested ; 2049current_sctx = ac -> script_ctx ; 2050apc -> script_ctx = current_sctx ; 2051 2052char * retval ; 2053if (ac -> handler_cmd ) { 2054retval = xstrdup (ac -> handler_cmd ); 2055 }else { 2056AutoCmd ac_copy = * ac ; 2057// Mark oneshot handler as "removed" now, to prevent recursion by e.g. `:doautocmd`. #25526 2058ac -> pat = oneshot ?NULL :ac -> pat ; 2059// May reallocate `acs` kvec_t data and invalidate the `ac` pointer. 2060bool rv = au_callback (& ac_copy ,apc ); 2061if (oneshot ) { 2062// Restore `pat`. Use `acs` because `ac` may have been invalidated by the callback. 2063kv_A (* acs ,apc -> auidx ).pat = ac_copy .pat ; 2064 } 2065// If an autocommand callback returns true, delete the autocommand 2066oneshot = oneshot || rv ; 2067 2068// HACK(tjdevries): 2069// We just return "not-null" and continue going. 2070// This would be a good candidate for a refactor. You would need to refactor: 2071// 1. do_cmdline to accept something besides a string 2072// OR 2073// 2. make where we call do_cmdline for autocmds not have to return anything, 2074// and instead we loop over all the matches and just execute one-by-one. 2075// However, my expectation would be that could be expensive. 2076retval = xcalloc (1 ,1 ); 2077 } 2078 2079// Remove one-shot ("once") autocmd in anticipation of its execution. 2080if (oneshot ) { 2081aucmd_del (& kv_A (* acs ,apc -> auidx )); 2082 } 2083 2084if (apc -> auidx < apc -> ausize ) { 2085apc -> auidx ++ ; 2086 }else { 2087apc -> auidx = SIZE_MAX ; 2088 } 2089 2090return retval ; 2091} 2092 2093/// Return true if there is a matching autocommand for "fname". 2094/// To account for buffer-local autocommands, function needs to know 2095/// in which buffer the file will be opened. 2096/// 2097/// @param event event that occurred. 2098/// @param sfname filename the event occurred in. 2099/// @param buf buffer the file is open in 2100bool has_autocmd (event_T event ,char * sfname ,buf_T * buf ) 2101FUNC_ATTR_WARN_UNUSED_RESULT 2102{ 2103char * tail = path_tail (sfname ); 2104bool retval = false; 2105 2106char * fname = FullName_save (sfname , false); 2107if (fname == NULL ) { 2108return false; 2109 } 2110 2111AutoCmdVec * const acs = & autocmds [(int )event ]; 2112for (size_t i = 0 ;i < kv_size (* acs );i ++ ) { 2113AutoPat * const ap = kv_A (* acs ,i ).pat ; 2114if (ap != NULL 2115&& (ap -> buflocal_nr == 0 2116 ?match_file_pat (NULL ,& ap -> reg_prog ,fname ,sfname ,tail ,ap -> allow_dirs ) 2117 :buf != NULL && ap -> buflocal_nr == buf -> b_fnum )) { 2118retval = true; 2119break ; 2120 } 2121 } 2122 2123xfree (fname ); 2124 2125return retval ; 2126} 2127 2128// Function given to ExpandGeneric() to obtain the list of autocommand group names. 2129char * expand_get_augroup_name (expand_T * xp ,int idx ) 2130{ 2131 (void )xp ;// Required for ExpandGeneric 2132return augroup_name (idx + 1 ); 2133} 2134 2135/// @param doautocmd true for :doauto*, false for :autocmd 2136char * aucmd_set_expand_context (expand_T * xp ,char * arg ,bool doautocmd ) 2137{ 2138// check for a group name, skip it if present 2139autocmd_include_groups = false; 2140char * p = arg ; 2141int group = arg_augroup_get (& arg ); 2142 2143// If there only is a group name that's what we expand. 2144if (* arg == NUL && group != AUGROUP_ALL && !ascii_iswhite (arg [-1 ])) { 2145arg = p ; 2146group = AUGROUP_ALL ; 2147 } 2148 2149// skip over event name 2150for (p = arg ;* p != NUL && !ascii_iswhite (* p );p ++ ) { 2151if (* p == ',' ) { 2152arg = p + 1 ; 2153 } 2154 } 2155if (* p == NUL ) { 2156if (group == AUGROUP_ALL ) { 2157autocmd_include_groups = true; 2158 } 2159xp -> xp_context = EXPAND_EVENTS ;// expand event name 2160xp -> xp_pattern = arg ; 2161return NULL ; 2162 } 2163 2164// skip over pattern 2165arg = skipwhite (p ); 2166while (* arg && (!ascii_iswhite (* arg )|| arg [-1 ]== '\\' )) { 2167arg ++ ; 2168 } 2169if (* arg ) { 2170return arg ;// expand (next) command 2171 } 2172 2173if (doautocmd ) { 2174xp -> xp_context = EXPAND_FILES ;// expand file names 2175 }else { 2176xp -> xp_context = EXPAND_NOTHING ;// pattern is not expanded 2177 } 2178return NULL ; 2179} 2180 2181/// Function given to ExpandGeneric() to obtain the list of event names. 2182char * expand_get_event_name (expand_T * xp ,int idx ) 2183{ 2184 (void )xp ;// xp is a required parameter to be used with ExpandGeneric 2185 2186// List group names 2187char * name = augroup_name (idx + 1 ); 2188if (name != NULL ) { 2189// skip when not including groups or skip deleted entries 2190if (!autocmd_include_groups || name == get_deleted_augroup ()) { 2191return "" ; 2192 } 2193 2194return name ; 2195 } 2196 2197int i = idx - next_augroup_id ; 2198if (i < 0 || i >=NUM_EVENTS ) { 2199return NULL ; 2200 } 2201 2202// List event names 2203return event_names [i ].name ; 2204} 2205 2206/// Function given to ExpandGeneric() to obtain the list of event names. Don't 2207/// include groups. 2208char * get_event_name_no_group (expand_T * xp FUNC_ATTR_UNUSED ,int idx ,bool win ) 2209{ 2210if (idx < 0 || idx >=NUM_EVENTS ) { 2211return NULL ; 2212 } 2213 2214if (!win ) { 2215return event_names [idx ].name ; 2216 } 2217 2218// Need to check subset of allowed values for 'eventignorewin'. 2219int j = 0 ; 2220for (int i = 0 ;i < NUM_EVENTS ;i ++ ) { 2221j += event_names [i ].event <=0 ; 2222if (j == idx + 1 ) { 2223return event_names [i ].name ; 2224 } 2225 } 2226return NULL ; 2227} 2228 2229/// Check whether given autocommand is supported 2230/// 2231/// @param[in] event Event to check. 2232/// 2233/// @return True if it is, false otherwise. 2234bool autocmd_supported (const char * const event ) 2235FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 2236{ 2237char * p ; 2238return event_name2nr (event ,& p )!= NUM_EVENTS ; 2239} 2240 2241/// Return true if an autocommand is defined for a group, event and 2242/// pattern: The group can be omitted to accept any group. 2243/// `event` and `pattern` can be omitted to accept any event and pattern. 2244/// Buffer-local patterns <buffer> or <buffer=N> are accepted. 2245/// Used for: 2246/// exists("#Group") or 2247/// exists("#Group#Event") or 2248/// exists("#Group#Event#pat") or 2249/// exists("#Event") or 2250/// exists("#Event#pat") 2251/// 2252/// @param arg autocommand string 2253bool au_exists (const char * const arg ) 2254FUNC_ATTR_WARN_UNUSED_RESULT 2255{ 2256buf_T * buflocal_buf = NULL ; 2257bool retval = false; 2258 2259// Make a copy so that we can change the '#' chars to a NUL. 2260char * const arg_save = xstrdup (arg ); 2261char * p = strchr (arg_save ,'#' ); 2262if (p != NULL ) { 2263* p ++ = NUL ; 2264 } 2265 2266// First, look for an autocmd group name. 2267int group = augroup_find (arg_save ); 2268char * event_name ; 2269if (group == AUGROUP_ERROR ) { 2270// Didn't match a group name, assume the first argument is an event. 2271group = AUGROUP_ALL ; 2272event_name = arg_save ; 2273 }else { 2274if (p == NULL ) { 2275// "Group": group name is present and it's recognized 2276retval = true; 2277 gototheend ; 2278 } 2279 2280// Must be "Group#Event" or "Group#Event#pat". 2281event_name = p ; 2282p = strchr (event_name ,'#' ); 2283if (p != NULL ) { 2284* p ++ = NUL ;// "Group#Event#pat" 2285 } 2286 } 2287 2288char * pattern = p ;// "pattern" is NULL when there is no pattern. 2289 2290// Find the index (enum) for the event name. 2291event_T event = event_name2nr (event_name ,& p ); 2292 2293// return false if the event name is not recognized 2294if (event == NUM_EVENTS ) { 2295 gototheend ; 2296 } 2297 2298// Find the first autocommand for this event. 2299// If there isn't any, return false; 2300// If there is one and no pattern given, return true; 2301AutoCmdVec * const acs = & autocmds [(int )event ]; 2302if (kv_size (* acs )== 0 ) { 2303 gototheend ; 2304 } 2305 2306// if pattern is "<buffer>", special handling is needed which uses curbuf 2307// for pattern "<buffer=N>, mb_strcmp_ic() will work fine 2308if (pattern != NULL && STRICMP (pattern ,"<buffer>" )== 0 ) { 2309buflocal_buf = curbuf ; 2310 } 2311 2312// Check if there is an autocommand with the given pattern. 2313for (size_t i = 0 ;i < kv_size (* acs );i ++ ) { 2314AutoPat * const ap = kv_A (* acs ,i ).pat ; 2315// Only use a pattern when it has not been removed. 2316// Patterns are matched verbatim (like do_autocmd): mb_strcmp_ic instead of path_equal. 2317if (ap != NULL 2318&& (group == AUGROUP_ALL || ap -> group == group ) 2319&& (pattern == NULL 2320|| (buflocal_buf == NULL 2321 ?mb_strcmp_ic (p_fic ,ap -> pat ,pattern )== 0 2322 :ap -> buflocal_nr == buflocal_buf -> b_fnum ))) { 2323retval = true; 2324break ; 2325 } 2326 } 2327 2328theend : 2329xfree (arg_save ); 2330return retval ; 2331} 2332 2333// Checks if a pattern is buflocal 2334bool aupat_is_buflocal (const char * pat ,int patlen ) 2335FUNC_ATTR_PURE 2336{ 2337return patlen >=8 && strncmp (pat ,"<buffer" ,7 )== 0 && pat [patlen - 1 ]== '>' ; 2338} 2339 2340int aupat_get_buflocal_nr (const char * pat ,int patlen ) 2341{ 2342assert (aupat_is_buflocal (pat ,patlen )); 2343 2344// "<buffer>" 2345if (patlen == 8 ) { 2346return curbuf -> b_fnum ; 2347 } 2348 2349if (patlen > 9 && pat [7 ]== '=' ) { 2350// "<buffer=abuf>" 2351if (patlen == 13 && STRNICMP (pat ,"<buffer=abuf>" ,13 )== 0 ) { 2352return autocmd_bufnr ; 2353 } 2354 2355// "<buffer=123>" 2356if (skipdigits (pat + 8 )== pat + patlen - 1 ) { 2357char * p = (char * )pat + 8 ; 2358return getdigits_int (& p , false,0 ); 2359 } 2360 } 2361 2362return 0 ; 2363} 2364 2365// normalize buffer pattern 2366void aupat_normalize_buflocal_pat (char * dest ,const char * pat ,int patlen ,int buflocal_nr ) 2367{ 2368assert (aupat_is_buflocal (pat ,patlen )); 2369 2370if (buflocal_nr == 0 ) { 2371buflocal_nr = curbuf -> handle ; 2372 } 2373 2374// normalize pat into standard "<buffer>#N" form 2375snprintf (dest ,BUFLOCAL_PAT_LEN ,"<buffer=%d>" ,buflocal_nr ); 2376} 2377 2378int autocmd_delete_event (int group ,event_T event ,const char * pat ) 2379FUNC_ATTR_NONNULL_ALL 2380{ 2381return do_autocmd_event (event ,pat , false, false,"" , true,group ); 2382} 2383 2384/// Deletes an autocmd by ID. 2385/// Only autocmds created via the API have IDs associated with them. There 2386/// is no way to delete a specific autocmd created via :autocmd 2387bool autocmd_delete_id (int64_t id ) 2388{ 2389assert (id > 0 ); 2390bool success = false; 2391 2392// Note that since multiple AutoCmd objects can have the same ID, we need to do a full scan. 2393FOR_ALL_AUEVENTS (event ) { 2394AutoCmdVec * const acs = & autocmds [(int )event ]; 2395for (size_t i = 0 ;i < kv_size (* acs );i ++ ) { 2396AutoCmd * const ac = & kv_A (* acs ,i ); 2397if (ac -> id == id ) { 2398aucmd_del (ac ); 2399success = true; 2400 } 2401 } 2402 } 2403return success ; 2404} 2405 2406/// Gets an (allocated) string representation of an autocmd command/callback. 2407char * aucmd_handler_to_string (AutoCmd * ac ) 2408FUNC_ATTR_PURE 2409{ 2410if (ac -> handler_cmd ) { 2411return xstrdup (ac -> handler_cmd ); 2412 } 2413return callback_to_string (& ac -> handler_fn ,NULL ); 2414} 2415 2416// Arg Parsing Functions 2417 2418/// Scan over the events. "*" stands for all events. 2419/// true when group name was found 2420static char * arg_event_skip (char * arg ,bool have_group ) 2421{ 2422char * pat ; 2423char * p ; 2424 2425if (* arg == '*' ) { 2426if (arg [1 ]&& !ascii_iswhite (arg [1 ])) { 2427semsg (_ ("E215: Illegal character after *: %s" ),arg ); 2428return NULL ; 2429 } 2430pat = arg + 1 ; 2431 }else { 2432for (pat = arg ;* pat && * pat != '|' && !ascii_iswhite (* pat );pat = p ) { 2433if ((int )event_name2nr (pat ,& p ) >=NUM_EVENTS ) { 2434if (have_group ) { 2435semsg (_ ("E216: No such event: %s" ),pat ); 2436 }else { 2437semsg (_ ("E216: No such group or event: %s" ),pat ); 2438 } 2439return NULL ; 2440 } 2441 } 2442 } 2443return pat ; 2444} 2445 2446// Find the group ID in a ":autocmd" or ":doautocmd" argument. 2447// The "argp" argument is advanced to the following argument. 2448// 2449// Returns the group ID or AUGROUP_ALL. 2450static int arg_augroup_get (char ** argp ) 2451{ 2452char * p ; 2453char * arg = * argp ; 2454 2455for (p = arg ;* p && !ascii_iswhite (* p )&& * p != '|' ;p ++ ) {} 2456if (p <=arg ) { 2457return AUGROUP_ALL ; 2458 } 2459 2460char * group_name = xmemdupz (arg , (size_t )(p - arg )); 2461int group = augroup_find (group_name ); 2462if (group == AUGROUP_ERROR ) { 2463group = AUGROUP_ALL ;// no match, use all groups 2464 }else { 2465* argp = skipwhite (p );// match, skip over group name 2466 } 2467xfree (group_name ); 2468return group ; 2469} 2470 2471/// Handles grabbing arguments from `:autocmd` such as ++once and ++nested 2472static bool arg_autocmd_flag_get (bool * flag ,char ** cmd_ptr ,char * pattern ,int len ) 2473{ 2474if (strncmp (* cmd_ptr ,pattern , (size_t )len )== 0 && ascii_iswhite ((* cmd_ptr )[len ])) { 2475if (* flag ) { 2476semsg (_ (e_duparg2 ),pattern ); 2477return true; 2478 } 2479 2480* flag = true; 2481* cmd_ptr = skipwhite (* cmd_ptr + len ); 2482 } 2483 2484return false; 2485} 2486 2487/// When kFalse: VimSuspend should be triggered next. 2488/// When kTrue: VimResume should be triggered next. 2489/// When kNone: Currently triggering VimSuspend or VimResume. 2490static TriState pending_vimresume = kFalse ; 2491 2492static void vimresume_event (void ** argv ) 2493{ 2494apply_autocmds (EVENT_VIMRESUME ,NULL ,NULL , false,NULL ); 2495pending_vimresume = kFalse ; 2496} 2497 2498/// Trigger VimSuspend or VimResume autocommand. 2499void may_trigger_vim_suspend_resume (bool suspend ) 2500{ 2501if (suspend && pending_vimresume == kFalse ) { 2502pending_vimresume = kNone ; 2503apply_autocmds (EVENT_VIMSUSPEND ,NULL ,NULL , false,NULL ); 2504pending_vimresume = kTrue ; 2505 }else if (!suspend && pending_vimresume == kTrue ) { 2506pending_vimresume = kNone ; 2507multiqueue_put (main_loop .events ,vimresume_event ,NULL ); 2508 } 2509} 2510 2511// UI Enter 2512void do_autocmd_uienter (uint64_t chanid ,bool attached ) 2513{ 2514static bool recursive = false; 2515 2516if (starting == NO_SCREEN ) { 2517return ;// user config hasn't been sourced yet 2518 } 2519if (recursive ) { 2520return ;// disallow recursion 2521 } 2522recursive = true; 2523 2524save_v_event_T save_v_event ; 2525dict_T * dict = get_v_event (& save_v_event ); 2526assert (chanid < VARNUMBER_MAX ); 2527tv_dict_add_nr (dict ,S_LEN ("chan" ), (varnumber_T )chanid ); 2528tv_dict_set_keys_readonly (dict ); 2529apply_autocmds (attached ?EVENT_UIENTER :EVENT_UILEAVE ,NULL ,NULL , false,curbuf ); 2530restore_v_event (dict ,& save_v_event ); 2531 2532recursive = false; 2533} 2534 2535// FocusGained 2536 2537void do_autocmd_focusgained (bool gained ) 2538{ 2539static bool recursive = false; 2540static Timestamp last_time = 0 ; 2541 2542if (recursive ) { 2543return ;// disallow recursion 2544 } 2545recursive = true; 2546apply_autocmds ((gained ?EVENT_FOCUSGAINED :EVENT_FOCUSLOST ),NULL ,NULL , false,curbuf ); 2547 2548// When activated: Check if any file was modified outside of Vim. 2549// Only do this when not done within the last two seconds as: 2550// 1. Some filesystems have modification time granularity in seconds. Fat32 2551// has a granularity of 2 seconds. 2552// 2. We could get multiple notifications in a row. 2553if (gained && last_time + (Timestamp )2000 < os_now ()) { 2554check_timestamps (true); 2555last_time = os_now (); 2556 } 2557 2558recursive = false; 2559} 2560 2561/// @return Whether any FileType autocommands were executed. 2562bool do_filetype_autocmd (buf_T * buf ,bool force ) 2563{ 2564static int ft_recursive = 0 ; 2565 2566if (ft_recursive > 0 && !force ) { 2567return false;// disallow recursion 2568 } 2569 2570int secure_save = secure ; 2571 2572// Reset the secure flag, since the value of 'filetype' has 2573// been checked to be safe. 2574secure = 0 ; 2575 2576ft_recursive ++ ; 2577buf -> b_did_filetype = true; 2578// Only pass true for "force" when it is true or 2579// used recursively, to avoid endless recurrence. 2580bool ret 2581= apply_autocmds (EVENT_FILETYPE ,buf -> b_p_ft ,buf -> b_fname ,force || ft_recursive == 1 ,buf ); 2582ft_recursive -- ; 2583 2584secure = secure_save ; 2585return ret ; 2586}