robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// Code to handle tags and the tag stack 2 3#include <assert.h> 4#include <ctype.h> 5#include <inttypes.h> 6#include <stdbool.h> 7#include <stdio.h> 8#include <stdlib.h> 9#include <string.h> 10 11#include "nvim/ascii_defs.h" 12#include "nvim/autocmd.h" 13#include "nvim/autocmd_defs.h" 14#include "nvim/buffer.h" 15#include "nvim/buffer_defs.h" 16#include "nvim/charset.h" 17#include "nvim/cmdexpand.h" 18#include "nvim/cmdexpand_defs.h" 19#include "nvim/cursor.h" 20#include "nvim/dialog.h" 21#include "nvim/drawscreen.h" 22#include "nvim/errors.h" 23#include "nvim/eval.h" 24#include "nvim/eval/typval.h" 25#include "nvim/eval/vars.h" 26#include "nvim/ex_cmds.h" 27#include "nvim/ex_cmds_defs.h" 28#include "nvim/ex_docmd.h" 29#include "nvim/file_search.h" 30#include "nvim/fileio.h" 31#include "nvim/fold.h" 32#include "nvim/garray.h" 33#include "nvim/garray_defs.h" 34#include "nvim/gettext_defs.h" 35#include "nvim/globals.h" 36#include "nvim/hashtab.h" 37#include "nvim/hashtab_defs.h" 38#include "nvim/help.h" 39#include "nvim/highlight_defs.h" 40#include "nvim/insexpand.h" 41#include "nvim/lua/executor.h" 42#include "nvim/macros_defs.h" 43#include "nvim/mark.h" 44#include "nvim/mark_defs.h" 45#include "nvim/mbyte.h" 46#include "nvim/mbyte_defs.h" 47#include "nvim/memory.h" 48#include "nvim/message.h" 49#include "nvim/move.h" 50#include "nvim/option.h" 51#include "nvim/option_defs.h" 52#include "nvim/option_vars.h" 53#include "nvim/optionstr.h" 54#include "nvim/os/fs.h" 55#include "nvim/os/input.h" 56#include "nvim/os/os_defs.h" 57#include "nvim/os/time.h" 58#include "nvim/path.h" 59#include "nvim/pos_defs.h" 60#include "nvim/quickfix.h" 61#include "nvim/regexp.h" 62#include "nvim/regexp_defs.h" 63#include "nvim/runtime.h" 64#include "nvim/search.h" 65#include "nvim/state_defs.h" 66#include "nvim/strings.h" 67#include "nvim/tag.h" 68#include "nvim/types_defs.h" 69#include "nvim/ui.h" 70#include "nvim/vim_defs.h" 71#include "nvim/window.h" 72 73// Structure to hold pointers to various items in a tag line. 74typedef struct { 75// filled in by parse_tag_line(): 76char * tagname ;// start of tag name (skip "file:") 77char * tagname_end ;// char after tag name 78char * fname ;// first char of file name 79char * fname_end ;// char after file name 80char * command ;// first char of command 81// filled in by parse_match(): 82char * command_end ;// first char after command 83char * tag_fname ;// file name of the tags file. This is used 84// when 'tr' is set. 85char * tagkind ;// "kind:" value 86char * tagkind_end ;// end of tagkind 87char * user_data ;// user_data string 88char * user_data_end ;// end of user_data 89linenr_T tagline ;// "line:" value 90}tagptrs_T ; 91 92// Structure to hold info about the tag pattern being used. 93typedef struct { 94char * pat ;// the pattern 95int len ;// length of pat[] 96char * head ;// start of pattern head 97int headlen ;// length of head[] 98regmatch_T regmatch ;// regexp program, may be NULL 99}pat_T ; 100 101// The matching tags are first stored in one of the hash tables. In 102// which one depends on the priority of the match. 103// ht_match[] is used to find duplicates, ga_match[] to keep them in sequence. 104// At the end, the matches from ga_match[] are concatenated, to make a list 105// sorted on priority. 106enum { 107MT_ST_CUR = 0 ,// static match in current file 108MT_GL_CUR = 1 ,// global match in current file 109MT_GL_OTH = 2 ,// global match in other file 110MT_ST_OTH = 3 ,// static match in other file 111MT_IC_OFF = 4 ,// add for icase match 112MT_RE_OFF = 8 ,// add for regexp match 113MT_MASK = 7 ,// mask for printing priority 114MT_COUNT = 16 , 115}; 116 117static char * mt_names [MT_COUNT /2 ]= 118{"FSC" ,"F C" ,"F " ,"FS " ," SC" ," C" ," " ," S " }; 119 120#define NOTAGFILE 99 // return value for jumpto_tag 121static char * nofile_fname = NULL ;// fname for NOTAGFILE error 122 123/// Classification of a "cmd" value returned by a tagfunc. 124typedef enum { 125TAGCMD_INVALID ,///< cannot be stored in a tag line 126TAGCMD_ADDRESS ,///< line number or /pat/ or ?pat? (no "|" needed) 127TAGCMD_GENERIC ,///< any other Ex command: needs a "|" terminator 128}tagcmd_T ; 129 130/// Return values used when reading lines from a tags file. 131typedef enum { 132TAGS_READ_SUCCESS = 1 , 133TAGS_READ_EOF , 134TAGS_READ_IGNORE , 135}tags_read_status_T ; 136 137/// States used during a tags search 138typedef enum { 139TS_START ,///< at start of file 140TS_LINEAR ,///< linear searching forward, till EOF 141TS_BINARY ,///< binary searching 142TS_SKIP_BACK ,///< skipping backwards 143TS_STEP_FORWARD ,///< stepping forwards 144}tagsearch_state_T ; 145 146/// Binary search file offsets in a tags file 147typedef struct { 148off_T low_offset ;///< offset for first char of first line that 149///< could match 150off_T high_offset ;///< offset of char after last line that could 151///< match 152off_T curr_offset ;///< Current file offset in search range 153off_T curr_offset_used ;///< curr_offset used when skipping back 154off_T match_offset ;///< Where the binary search found a tag 155int low_char ;///< first char at low_offset 156int high_char ;///< first char at high_offset 157}tagsearch_info_T ; 158 159/// Return values used when matching tags against a pattern. 160typedef enum { 161TAG_MATCH_SUCCESS = 1 , 162TAG_MATCH_FAIL , 163TAG_MATCH_STOP , 164TAG_MATCH_NEXT , 165}tagmatch_status_T ; 166 167/// Arguments used for matching tags read from a tags file against a pattern. 168typedef struct { 169int matchoff ;///< tag match offset 170bool match_re ;///< true if the tag matches a regexp 171bool match_no_ic ;///< true if the tag matches with case 172bool has_re ;///< regular expression used 173bool sortic ;///< tags file sorted ignoring case (foldcase) 174bool sort_error ;///< tags file not sorted 175}findtags_match_args_T ; 176 177/// State information used during a tag search 178typedef struct { 179tagsearch_state_T state ;///< tag search state 180bool stop_searching ;///< stop when match found or error 181pat_T * orgpat ;///< holds unconverted pattern info 182char * lbuf ;///< line buffer 183int lbuf_size ;///< length of lbuf 184char * tag_fname ;///< name of the tag file 185FILE * fp ;///< current tags file pointer 186int flags ;///< flags used for tag search 187int tag_file_sorted ;///< !_TAG_FILE_SORTED value 188bool get_searchpat ;///< used for 'showfulltag' 189bool help_only ;///< only search for help tags 190bool did_open ;///< did open a tag file 191int mincount ;///< MAXCOL: find all matches 192///< other: minimal number of matches 193bool linear ;///< do a linear search 194vimconv_T vimconv ; 195char help_lang [3 ];///< lang of current tags file 196int help_pri ;///< help language priority 197char * help_lang_find ;///< lang to be found 198bool is_txt ;///< flag of file extension 199int match_count ;///< number of matches found 200garray_T ga_match [MT_COUNT ];///< stores matches in sequence 201hashtab_T ht_match [MT_COUNT ];///< stores matches by key 202}findtags_state_T ; 203 204#include "tag.c.generated.h" 205 206static const char e_tag_stack_empty [] 207= N_ ("E73: Tag stack empty" ); 208static const char e_tag_not_found_str [] 209= N_ ("E426: Tag not found: %s" ); 210static const char e_at_bottom_of_tag_stack [] 211= N_ ("E555: At bottom of tag stack" ); 212static const char e_at_top_of_tag_stack [] 213= N_ ("E556: At top of tag stack" ); 214static const char e_cannot_modify_tag_stack_within_tagfunc [] 215= N_ ("E986: Cannot modify the tag stack within tagfunc" ); 216static const char e_invalid_return_value_from_tagfunc [] 217= N_ ("E987: Invalid return value from tagfunc" ); 218static const char e_window_unexpectedly_close_while_searching_for_tags [] 219= N_ ("E1299: Window unexpectedly closed while searching for tags" ); 220 221static char * tagmatchname = NULL ;// name of last used tag 222 223// Tag for preview window is remembered separately, to avoid messing up the 224// normal tagstack. 225static taggy_T ptag_entry = {NULL ,INIT_FMARK ,0 ,0 ,NULL }; 226 227static bool tfu_in_use = false;// disallow recursive call of tagfunc 228 229// Used instead of NUL to separate tag fields in the growarrays. 230#define TAG_SEP 0x02 231 232#ifdef EXITFREE 233void free_tagfunc_option (void ) 234{ 235callback_free (& p_tfu ); 236} 237#endif 238 239/// Mark the global 'tagfunc' callback with "copyID" so that it is not garbage 240/// collected. 241bool set_ref_in_tagfunc (int copyID ) 242{ 243return set_ref_in_callback (& p_tfu ,copyID ,NULL ,NULL ); 244} 245 246/// Jump to tag; handling of tag commands and tag stack 247/// 248/// *tag != NUL: ":tag {tag}", jump to new tag, add to tag stack 249/// 250/// type == DT_TAG: ":tag [tag]", jump to newer position or same tag again 251/// type == DT_HELP: like DT_TAG, but don't use regexp. 252/// type == DT_POP: ":pop" or CTRL-T, jump to old position 253/// type == DT_NEXT: jump to next match of same tag 254/// type == DT_PREV: jump to previous match of same tag 255/// type == DT_FIRST: jump to first match of same tag 256/// type == DT_LAST: jump to last match of same tag 257/// type == DT_SELECT: ":tselect [tag]", select tag from a list of all matches 258/// type == DT_JUMP: ":tjump [tag]", jump to tag or select tag from a list 259/// type == DT_LTAG: use location list for displaying tag matches 260/// type == DT_FREE: free cached matches 261/// 262/// @param eap excmd args (forwarded to Lua); may be NULL when the caller is not an excmd (e.g. `<C-T>`). 263/// @param tag tag (pattern) to jump to 264/// @param forceit :ta with ! 265/// @param verbose print "tag not found" message 266void do_tag (exarg_T * eap ,char * tag ,int type ,int count ,int forceit ,bool verbose ) 267{ 268taggy_T * tagstack = curwin -> w_tagstack ; 269int tagstackidx = curwin -> w_tagstackidx ; 270int tagstacklen = curwin -> w_tagstacklen ; 271int cur_match = 0 ; 272int cur_fnum = curbuf -> b_fnum ; 273int oldtagstackidx = tagstackidx ; 274int prevtagstackidx = tagstackidx ; 275bool new_tag = false; 276bool no_regexp = false; 277int error_cur_match = 0 ; 278bool save_pos = false; 279fmark_T saved_fmark ; 280int new_num_matches ; 281char ** new_matches ; 282bool use_tagstack ; 283bool skip_msg = false; 284char * buf_ffname = curbuf -> b_ffname ;// name for priority computation 285bool use_tfu = true; 286char * tofree = NULL ; 287 288// remember the matches for the last used tag 289static int num_matches = 0 ; 290static int max_num_matches = 0 ;// limit used for match search 291static char ** matches = NULL ; 292static int flags ; 293 294#ifdef EXITFREE 295if (type == DT_FREE ) { 296// remove the list of matches 297FreeWild (num_matches ,matches ); 298num_matches = 0 ; 299return ; 300 } 301#endif 302 303if (tfu_in_use ) { 304emsg (_ (e_cannot_modify_tag_stack_within_tagfunc )); 305return ; 306 } 307 308if (postponed_split == 0 && !check_can_set_curbuf_forceit (forceit )) { 309return ; 310 } 311 312if (type == DT_HELP ) { 313type = DT_TAG ; 314no_regexp = true; 315use_tfu = false; 316 } 317 318int prev_num_matches = num_matches ; 319free_string_option (nofile_fname ); 320nofile_fname = NULL ; 321 322clearpos (& saved_fmark .mark );// shutup gcc 4.0 323saved_fmark .fnum = 0 ; 324saved_fmark .view = (fmarkv_T )INIT_FMARKV ; 325 326// Don't add a tag to the tagstack if 'tagstack' has been reset. 327assert (tag != NULL ); 328if (!p_tgst && * tag != NUL ) { 329use_tagstack = false; 330new_tag = true; 331if (g_do_tagpreview != 0 ) { 332tagstack_clear_entry (& ptag_entry ); 333ptag_entry .tagname = xstrdup (tag ); 334 } 335 }else { 336if (g_do_tagpreview != 0 ) { 337use_tagstack = false; 338 }else { 339use_tagstack = true; 340 } 341 342// new pattern, add to the tag stack 343if (* tag != NUL 344&& (type == DT_TAG || type == DT_SELECT || type == DT_JUMP 345|| type == DT_LTAG )) { 346if (g_do_tagpreview != 0 ) { 347if (ptag_entry .tagname != NULL 348&& strcmp (ptag_entry .tagname ,tag )== 0 ) { 349// Jumping to same tag: keep the current match, so that 350// the CursorHold autocommand example works. 351cur_match = ptag_entry .cur_match ; 352cur_fnum = ptag_entry .cur_fnum ; 353 }else { 354tagstack_clear_entry (& ptag_entry ); 355ptag_entry .tagname = xstrdup (tag ); 356 } 357 }else { 358// If the last used entry is not at the top, delete all tag 359// stack entries above it. 360while (tagstackidx < tagstacklen ) { 361tagstack_clear_entry (& tagstack [-- tagstacklen ]); 362 } 363 364// if the tagstack is full: remove oldest entry 365if (++ tagstacklen > TAGSTACKSIZE ) { 366tagstacklen = TAGSTACKSIZE ; 367tagstack_clear_entry (& tagstack [0 ]); 368for (int i = 1 ;i < tagstacklen ;i ++ ) { 369tagstack [i - 1 ]= tagstack [i ]; 370 } 371tagstack [-- tagstackidx ].user_data = NULL ; 372 } 373 374// put the tag name in the tag stack 375tagstack [tagstackidx ].tagname = xstrdup (tag ); 376 377curwin -> w_tagstacklen = tagstacklen ; 378 379save_pos = true;// save the cursor position below 380 } 381 382new_tag = true; 383 }else { 384if (g_do_tagpreview != 0 ?ptag_entry .tagname == NULL 385 :tagstacklen == 0 ) { 386// empty stack 387emsg (_ (e_tag_stack_empty )); 388 gotoend_do_tag ; 389 } 390 391if (type == DT_POP ) {// go to older position 392const bool old_KeyTyped = KeyTyped ; 393if ((tagstackidx -= count )< 0 ) { 394emsg (_ (e_at_bottom_of_tag_stack )); 395if (tagstackidx + count == 0 ) { 396// We did [num]^T from the bottom of the stack 397tagstackidx = 0 ; 398 gotoend_do_tag ; 399 } 400// We weren't at the bottom of the stack, so jump all the 401// way to the bottom now. 402tagstackidx = 0 ; 403 }else if (tagstackidx >=tagstacklen ) {// count == 0? 404emsg (_ (e_at_top_of_tag_stack )); 405 gotoend_do_tag ; 406 } 407 408// Make a copy of the fmark, autocommands may invalidate the 409// tagstack before it's used. 410saved_fmark = tagstack [tagstackidx ].fmark ; 411if (saved_fmark .fnum != curbuf -> b_fnum ) { 412// Jump to other file. If this fails (e.g. because the 413// file was changed) keep original position in tag stack. 414if (buflist_getfile (saved_fmark .fnum ,saved_fmark .mark .lnum , 415GETF_SETMARK ,forceit )== FAIL ) { 416tagstackidx = oldtagstackidx ;// back to old posn 417 gotoend_do_tag ; 418 } 419// A BufReadPost autocommand may jump to the '" mark, but 420// we don't what that here. 421curwin -> w_cursor .lnum = saved_fmark .mark .lnum ; 422 }else { 423setpcmark (); 424curwin -> w_cursor .lnum = saved_fmark .mark .lnum ; 425 } 426curwin -> w_cursor .col = saved_fmark .mark .col ; 427curwin -> w_set_curswant = true; 428if (jop_flags & kOptJopFlagView ) { 429mark_view_restore (& saved_fmark ); 430 } 431check_cursor (curwin ); 432if ((fdo_flags & kOptFdoFlagTag )&& old_KeyTyped ) { 433foldOpenCursor (); 434 } 435 436// remove the old list of matches 437FreeWild (num_matches ,matches ); 438num_matches = 0 ; 439tag_freematch (); 440 gotoend_do_tag ; 441 } 442 443if (type == DT_TAG 444|| type == DT_LTAG ) { 445if (g_do_tagpreview != 0 ) { 446cur_match = ptag_entry .cur_match ; 447cur_fnum = ptag_entry .cur_fnum ; 448 }else { 449// ":tag" (no argument): go to newer pattern 450save_pos = true;// save the cursor position below 451if ((tagstackidx += count - 1 ) >=tagstacklen ) { 452// Beyond the last one, just give an error message and 453// go to the last one. Don't store the cursor 454// position. 455tagstackidx = tagstacklen - 1 ; 456emsg (_ (e_at_top_of_tag_stack )); 457save_pos = false; 458 }else if (tagstackidx < 0 ) {// must have been count == 0 459emsg (_ (e_at_bottom_of_tag_stack )); 460tagstackidx = 0 ; 461 gotoend_do_tag ; 462 } 463cur_match = tagstack [tagstackidx ].cur_match ; 464cur_fnum = tagstack [tagstackidx ].cur_fnum ; 465 } 466new_tag = true; 467 }else {// go to other matching tag 468// Save index for when selection is cancelled. 469prevtagstackidx = tagstackidx ; 470 471if (g_do_tagpreview != 0 ) { 472cur_match = ptag_entry .cur_match ; 473cur_fnum = ptag_entry .cur_fnum ; 474 }else { 475if (-- tagstackidx < 0 ) { 476tagstackidx = 0 ; 477 } 478cur_match = tagstack [tagstackidx ].cur_match ; 479cur_fnum = tagstack [tagstackidx ].cur_fnum ; 480 } 481switch (type ) { 482case DT_FIRST : 483cur_match = count - 1 ;break ; 484case DT_SELECT : 485case DT_JUMP : 486case DT_LAST : 487cur_match = MAXCOL - 1 ;break ; 488case DT_NEXT : 489cur_match += count ;break ; 490case DT_PREV : 491cur_match -= count ;break ; 492 } 493if (cur_match >=MAXCOL ) { 494cur_match = MAXCOL - 1 ; 495 }else if (cur_match < 0 ) { 496emsg (_ ("E425: Cannot go before first matching tag" )); 497skip_msg = true; 498cur_match = 0 ; 499cur_fnum = curbuf -> b_fnum ; 500 } 501 } 502 } 503 504if (g_do_tagpreview != 0 ) { 505if (type != DT_SELECT && type != DT_JUMP ) { 506ptag_entry .cur_match = cur_match ; 507ptag_entry .cur_fnum = cur_fnum ; 508 } 509 }else { 510// For ":tag [arg]" or ":tselect" remember position before the jump. 511saved_fmark = tagstack [tagstackidx ].fmark ; 512if (save_pos ) { 513tagstack [tagstackidx ].fmark .mark = curwin -> w_cursor ; 514tagstack [tagstackidx ].fmark .fnum = curbuf -> b_fnum ; 515tagstack [tagstackidx ].fmark .view = mark_view_make (curwin ,curwin -> w_cursor ); 516 } 517 518// Curwin will change in the call to jumpto_tag() if ":stag" was 519// used or an autocommand jumps to another window; store value of 520// tagstackidx now. 521curwin -> w_tagstackidx = tagstackidx ; 522if (type != DT_SELECT && type != DT_JUMP ) { 523curwin -> w_tagstack [tagstackidx ].cur_match = cur_match ; 524curwin -> w_tagstack [tagstackidx ].cur_fnum = cur_fnum ; 525 } 526 } 527 } 528 529// When not using the current buffer get the name of buffer "cur_fnum". 530// Makes sure that the tag order doesn't change when using a remembered 531// position for "cur_match". 532if (cur_fnum != curbuf -> b_fnum ) { 533buf_T * buf = buflist_findnr (cur_fnum ); 534 535if (buf != NULL ) { 536buf_ffname = buf -> b_ffname ; 537 } 538 } 539 540// Repeat searching for tags, when a file has not been found. 541while (true) { 542char * name ; 543 544// When desired match not found yet, try to find it (and others). 545if (use_tagstack ) { 546// make a copy, the tagstack may change in 'tagfunc' 547name = xstrdup (tagstack [tagstackidx ].tagname ); 548xfree (tofree ); 549tofree = name ; 550 }else if (g_do_tagpreview != 0 ) { 551name = ptag_entry .tagname ; 552 }else { 553name = tag ; 554 } 555bool other_name = (tagmatchname == NULL || strcmp (tagmatchname ,name )!= 0 ); 556if (new_tag 557|| (cur_match >=num_matches && max_num_matches != MAXCOL ) 558|| other_name ) { 559if (other_name ) { 560xfree (tagmatchname ); 561tagmatchname = xstrdup (name ); 562 } 563 564if (type == DT_SELECT || type == DT_JUMP 565|| type == DT_LTAG ) { 566cur_match = MAXCOL - 1 ; 567 } 568max_num_matches = type == DT_TAG ?MAXCOL :cur_match + 1 ; 569 570// when the argument starts with '/', use it as a regexp 571if (!no_regexp && * name == '/' ) { 572flags = TAG_REGEXP ; 573name ++ ; 574 }else { 575flags = TAG_NOIC ; 576 } 577 578flags |=verbose ?TAG_VERBOSE :0 ; 579flags |= !use_tfu ?TAG_NO_TAGFUNC :0 ; 580 581if (find_tags (name ,& new_num_matches ,& new_matches ,flags , 582max_num_matches ,buf_ffname )== OK 583&& new_num_matches < max_num_matches ) { 584max_num_matches = MAXCOL ;// If less than max_num_matches 585// found: all matches found. 586 } 587 588// A tag function may do anything, which may cause various 589// information to become invalid. At least check for the tagstack 590// to still be the same. 591if (tagstack != curwin -> w_tagstack ) { 592emsg (_ (e_window_unexpectedly_close_while_searching_for_tags )); 593FreeWild (new_num_matches ,new_matches ); 594break ; 595 } 596 597// If there already were some matches for the same name, move them 598// to the start. Avoids that the order changes when using 599// ":tnext" and jumping to another file. 600if (!new_tag && !other_name ) { 601int idx = 0 ; 602tagptrs_T tagp ,tagp2 ; 603 604// Find the position of each old match in the new list. Need 605// to use parse_match() to find the tag line. 606for (int j = 0 ;j < num_matches ;j ++ ) { 607parse_match (matches [j ],& tagp ); 608for (int i = idx ;i < new_num_matches ;i ++ ) { 609parse_match (new_matches [i ],& tagp2 ); 610if (strcmp (tagp .tagname ,tagp2 .tagname )== 0 ) { 611char * p = new_matches [i ]; 612for (int k = i ;k > idx ;k -- ) { 613new_matches [k ]= new_matches [k - 1 ]; 614 } 615new_matches [idx ++ ]= p ; 616break ; 617 } 618 } 619 } 620 } 621FreeWild (num_matches ,matches ); 622num_matches = new_num_matches ; 623matches = new_matches ; 624 } 625 626if (num_matches <=0 ) { 627if (verbose ) { 628semsg (_ (e_tag_not_found_str ),name ); 629 } 630g_do_tagpreview = 0 ; 631 }else { 632if (type == DT_TAG && * tag != NUL ) { 633// If a count is supplied to the ":tag <name>" command, then 634// jump to count'th matching tag. 635cur_match = count > 0 ?count - 1 :0 ; 636 }else if (type == DT_SELECT || (type == DT_JUMP && num_matches > 1 )) { 637// Hand off to (async) vim.ui.select(). Roll back any pending tagstack changes. 638select_tag_match (eap ,new_tag ,use_tagstack ,num_matches ,matches ,name ); 639if (use_tagstack ) { 640tagstack [tagstackidx ].fmark = saved_fmark ; 641tagstackidx = prevtagstackidx ; 642 } 643break ; 644 }else if (type == DT_LTAG ) { 645if (add_llist_tags (tag ,num_matches ,matches )== FAIL ) { 646 gotoend_do_tag ; 647 } 648 649cur_match = 0 ;// Jump to the first tag 650 } 651 652if (cur_match >=num_matches ) { 653// Avoid giving this error when a file wasn't found and we're 654// looking for a match in another file, which wasn't found. 655// There will be an emsg("file doesn't exist") below then. 656if ((type == DT_NEXT || type == DT_FIRST ) 657&& nofile_fname == NULL ) { 658if (num_matches == 1 ) { 659emsg (_ ("E427: There is only one matching tag" )); 660 }else { 661emsg (_ ("E428: Cannot go beyond last matching tag" )); 662 } 663skip_msg = true; 664 } 665cur_match = num_matches - 1 ; 666 } 667if (use_tagstack ) { 668tagptrs_T tagp2 ; 669 670tagstack [tagstackidx ].cur_match = cur_match ; 671tagstack [tagstackidx ].cur_fnum = cur_fnum ; 672 673// store user-provided data originating from tagfunc 674if (use_tfu && parse_match (matches [cur_match ],& tagp2 )== OK 675&& tagp2 .user_data ) { 676XFREE_CLEAR (tagstack [tagstackidx ].user_data ); 677tagstack [tagstackidx ].user_data = 678xmemdupz (tagp2 .user_data , (size_t )(tagp2 .user_data_end - tagp2 .user_data )); 679 } 680 681tagstackidx ++ ; 682 }else if (g_do_tagpreview != 0 ) { 683ptag_entry .cur_match = cur_match ; 684ptag_entry .cur_fnum = cur_fnum ; 685 } 686 687// Only when going to try the next match, report that the previous 688// file didn't exist. Otherwise an emsg() is given below. 689if (nofile_fname != NULL && error_cur_match != cur_match ) { 690smsg (0 ,_ ("File \"%s\" does not exist" ),nofile_fname ); 691 } 692 693bool ic = (matches [cur_match ][0 ]& MT_IC_OFF ); 694if (type != DT_TAG && type != DT_SELECT && type != DT_JUMP 695&& (num_matches > 1 || ic ) 696&& !skip_msg ) { 697// Give an indication of the number of matching tags 698snprintf (IObuff ,sizeof (IObuff ),_ ("tag %d of %d%s" ), 699cur_match + 1 , 700num_matches , 701max_num_matches != MAXCOL ?_ (" or more" ) :"" ); 702if (ic ) { 703xstrlcat (IObuff ,_ (" Using tag with different case!" ),IOSIZE ); 704 } 705if ((num_matches > prev_num_matches || new_tag ) 706&& num_matches > 1 ) { 707msg (IObuff ,ic ?HLF_W :0 ); 708msg_scroll = true;// Don't overwrite this message. 709 }else { 710give_warning (IObuff ,ic , true); 711 } 712if (ic && !msg_scrolled && msg_silent == 0 ) { 713msg_delay (1007 , true); 714 } 715 } 716 717// Let the SwapExists event know what tag we are jumping to. 718size_t IObufflen = vim_snprintf_safelen (IObuff ,IOSIZE ,":ta %s\r" ,name ); 719set_vim_var_string (VV_SWAPCOMMAND ,IObuff , (ptrdiff_t )IObufflen ); 720 721// Jump to the desired match. 722int i = jumpto_tag (matches [cur_match ],forceit , true); 723 724set_vim_var_string (VV_SWAPCOMMAND ,NULL ,-1 ); 725 726if (i == NOTAGFILE ) { 727// File not found: try again with another matching tag 728if ((type == DT_PREV && cur_match > 0 ) 729|| ((type == DT_TAG || type == DT_NEXT 730|| type == DT_FIRST ) 731&& (max_num_matches != MAXCOL 732|| cur_match < num_matches - 1 ))) { 733error_cur_match = cur_match ; 734if (use_tagstack ) { 735tagstackidx -- ; 736 } 737if (type == DT_PREV ) { 738cur_match -- ; 739 }else { 740type = DT_NEXT ; 741cur_match ++ ; 742 } 743continue ; 744 } 745semsg (_ ("E429: File \"%s\" does not exist" ),nofile_fname ); 746 }else { 747// We may have jumped to another window, check that 748// tagstackidx is still valid. 749if (use_tagstack && tagstackidx > curwin -> w_tagstacklen ) { 750tagstackidx = curwin -> w_tagstackidx ; 751 } 752 } 753 } 754break ; 755 } 756 757end_do_tag : 758// Only store the new index when using the tagstack and it's valid. 759if (use_tagstack && tagstackidx <=curwin -> w_tagstacklen ) { 760curwin -> w_tagstackidx = tagstackidx ; 761 } 762postponed_split = 0 ;// don't split next time 763g_do_tagpreview = 0 ;// don't do tag preview next time 764xfree (tofree ); 765} 766 767/// Let the user pick from `matches`. Delegates to (async) `vim.ui.select()`. 768static void select_tag_match (exarg_T * eap ,bool new_tag ,bool use_tagstack ,int num_matches , 769char ** matches ,const char * name ) 770{ 771taggy_T * tagstack = curwin -> w_tagstack ; 772int tagstackidx = curwin -> w_tagstackidx ; 773 774typval_T items_tv ; 775tv_list_alloc_ret (& items_tv ,num_matches ); 776 777for (int i = 0 ;i < num_matches ;i ++ ) { 778os_breakcheck (); 779if (got_int ) { 780tv_clear (& items_tv ); 781return ; 782 } 783tagptrs_T tagp ; 784parse_match (matches [i ],& tagp ); 785 786bool cur = !new_tag 787&& ((g_do_tagpreview != 0 && i == ptag_entry .cur_match ) 788|| (use_tagstack && i == tagstack [tagstackidx ].cur_match )); 789 790dict_T * d = tv_dict_alloc (); 791tv_dict_add_str_len (d ,S_LEN ("tag" ),tagp .tagname , (int )(tagp .tagname_end - tagp .tagname )); 792tv_dict_add_str (d ,S_LEN ("pri" ),mt_names [matches [i ][0 ]& MT_MASK ]); 793if (tagp .tagkind != NULL ) { 794tv_dict_add_str_len (d ,S_LEN ("kind" ),tagp .tagkind , (int )(tagp .tagkind_end - tagp .tagkind )); 795 } 796char * fname = tag_full_fname (& tagp ); 797tv_dict_add_str (d ,S_LEN ("file" ),fname != NULL ?fname :"" ); 798xfree (fname ); 799tv_dict_add_bool (d ,S_LEN ("cur" ),cur ?kBoolVarTrue :kBoolVarFalse ); 800 801typval_T item = { .v_type = VAR_DICT , .vval .v_dict = d }; 802tv_list_append_tv (items_tv .vval .v_list ,& item ); 803 } 804 805// Pass items + tag name as a dict via the `extra` slot of nlua_call_excmd. Lua decides whether 806// to use `:tag` or `:stag` from `eap.name` (e.g. "tselect" vs "stselect"). 807dict_T * extra_d = tv_dict_alloc (); 808tv_dict_add_list (extra_d ,S_LEN ("items" ),items_tv .vval .v_list ); 809items_tv .vval .v_list -> lv_refcount ++ ;// dict keeps a ref 810tv_dict_add_str (extra_d ,S_LEN ("tagname" ),name ); 811typval_T extra_tv = { .v_type = VAR_DICT , .vval .v_dict = extra_d }; 812 813nlua_call_excmd ("vim._core.tag" ,"select_tag" ,eap ,& cmdmod ,& extra_tv ); 814 815tv_clear (& items_tv ); 816tv_clear (& extra_tv ); 817} 818 819/// Add the matching tags to the location list for the current 820/// window. 821static int add_llist_tags (char * tag ,int num_matches ,char ** matches ) 822{ 823char tag_name [128 + 1 ]; 824tagptrs_T tagp ; 825 826char * fname = xmalloc (MAXPATHL + 1 ); 827char * cmd = xmalloc (CMDBUFFSIZE + 1 ); 828list_T * list = tv_list_alloc (0 ); 829 830for (int i = 0 ;i < num_matches ;i ++ ) { 831dict_T * dict ; 832 833parse_match (matches [i ],& tagp ); 834 835// Save the tag name 836int len = MIN ((int )(tagp .tagname_end - tagp .tagname ),128 ); 837xmemcpyz (tag_name ,tagp .tagname , (size_t )len ); 838tag_name [len ]= NUL ; 839 840// Save the tag file name 841char * p = tag_full_fname (& tagp ); 842if (p == NULL ) { 843continue ; 844 } 845xstrlcpy (fname ,p ,MAXPATHL ); 846XFREE_CLEAR (p ); 847 848// Get the line number or the search pattern used to locate 849// the tag. 850linenr_T lnum = 0 ; 851if (isdigit ((uint8_t )(* tagp .command ))) { 852// Line number is used to locate the tag 853lnum = atoi (tagp .command ); 854 }else { 855// Search pattern is used to locate the tag 856 857// Locate the end of the command 858char * cmd_start = tagp .command ; 859char * cmd_end = tagp .command_end ; 860if (cmd_end == NULL ) { 861for (p = tagp .command ; 862* p && * p != '\r' && * p != '\n' ;p ++ ) {} 863cmd_end = p ; 864 } 865 866// Now, cmd_end points to the character after the 867// command. Adjust it to point to the last 868// character of the command. 869cmd_end -- ; 870 871// Skip the '/' and '?' characters at the 872// beginning and end of the search pattern. 873if (* cmd_start == '/' || * cmd_start == '?' ) { 874cmd_start ++ ; 875 } 876 877if (* cmd_end == '/' || * cmd_end == '?' ) { 878cmd_end -- ; 879 } 880 881len = 0 ; 882cmd [0 ]= NUL ; 883 884// If "^" is present in the tag search pattern, then 885// copy it first. 886if (* cmd_start == '^' ) { 887STRCPY (cmd ,"^" ); 888cmd_start ++ ; 889len ++ ; 890 } 891 892// Precede the tag pattern with \V to make it very 893// nomagic. 894strcat (cmd ,"\\V" ); 895len += 2 ; 896 897int cmd_len = MIN ((int )(cmd_end - cmd_start + 1 ),CMDBUFFSIZE - 5 ); 898snprintf (cmd + len , (size_t )(CMDBUFFSIZE + 1 - len ), 899"%.*s" ,cmd_len ,cmd_start ); 900len += cmd_len ; 901 902if (cmd [len - 1 ]== '$' ) { 903// Replace '$' at the end of the search pattern 904// with '\$' 905cmd [len - 1 ]= '\\' ; 906cmd [len ]= '$' ; 907len ++ ; 908 } 909 910cmd [len ]= NUL ; 911 } 912 913dict = tv_dict_alloc (); 914tv_list_append_dict (list ,dict ); 915 916tv_dict_add_str (dict ,S_LEN ("text" ),tag_name ); 917tv_dict_add_str (dict ,S_LEN ("filename" ),fname ); 918tv_dict_add_nr (dict ,S_LEN ("lnum" ),lnum ); 919if (lnum == 0 ) { 920tv_dict_add_str (dict ,S_LEN ("pattern" ),cmd ); 921 } 922 } 923 924vim_snprintf (IObuff ,IOSIZE ,"ltag %s" ,tag ); 925set_errorlist (curwin ,list ,' ' ,IObuff ,NULL ); 926 927tv_list_free (list ); 928XFREE_CLEAR (fname ); 929XFREE_CLEAR (cmd ); 930 931return OK ; 932} 933 934// Free cached tags. 935void tag_freematch (void ) 936{ 937XFREE_CLEAR (tagmatchname ); 938} 939 940static void taglen_advance (int l ) 941{ 942if (l == MAXCOL ) { 943msg_putchar ('\n' ); 944msg_advance (24 ); 945 }else { 946msg_advance (13 + l ); 947 } 948} 949 950// Print the tag stack 951void do_tags (exarg_T * eap ) 952{ 953taggy_T * tagstack = curwin -> w_tagstack ; 954int tagstackidx = curwin -> w_tagstackidx ; 955int tagstacklen = curwin -> w_tagstacklen ; 956 957// Highlight title 958msg_puts_title (_ ("\n # TO tag FROM line in file/text" )); 959for (int i = 0 ;i < tagstacklen ;i ++ ) { 960if (tagstack [i ].tagname != NULL ) { 961char * name = fm_getname (& (tagstack [i ].fmark ),30 ); 962if (name == NULL ) {// file name not available 963continue ; 964 } 965 966msg_putchar ('\n' ); 967vim_snprintf (IObuff ,IOSIZE ,"%c%2d %2d %-15s %5" PRIdLINENR " " , 968i == tagstackidx ?'>' :' ' , 969i + 1 , 970tagstack [i ].cur_match + 1 , 971tagstack [i ].tagname , 972tagstack [i ].fmark .mark .lnum ); 973msg_outtrans (IObuff ,0 , false); 974msg_outtrans (name ,tagstack [i ].fmark .fnum == curbuf -> b_fnum ?HLF_D :0 , false); 975xfree (name ); 976 } 977 } 978if (tagstackidx == tagstacklen ) {// idx at top of stack 979msg_puts ("\n>" ); 980 } 981} 982 983// Compare two strings, for length "len", ignoring case the ASCII way. 984// return 0 for match, < 0 for smaller, > 0 for bigger 985// Make sure case is folded to uppercase in comparison (like for 'sort -f') 986static int tag_strnicmp (char * s1 ,char * s2 ,size_t len ) 987{ 988while (len > 0 ) { 989int i = TOUPPER_ASC ((uint8_t )(* s1 ))- TOUPPER_ASC ((uint8_t )(* s2 )); 990if (i != 0 ) { 991return i ;// this character different 992 } 993if (* s1 == NUL ) { 994break ;// strings match until NUL 995 } 996s1 ++ ; 997s2 ++ ; 998len -- ; 999 } 1000return 0 ;// strings match 1001} 1002 1003// Extract info from the tag search pattern "pats->pat". 1004static void prepare_pats (pat_T * pats ,bool has_re ) 1005{ 1006pats -> head = pats -> pat ; 1007pats -> headlen = pats -> len ; 1008if (has_re ) { 1009// When the pattern starts with '^' or "\\<", binary searching can be 1010// used (much faster). 1011if (pats -> pat [0 ]== '^' ) { 1012pats -> head = pats -> pat + 1 ; 1013 }else if (pats -> pat [0 ]== '\\' && pats -> pat [1 ]== '<' ) { 1014pats -> head = pats -> pat + 2 ; 1015 } 1016if (pats -> head == pats -> pat ) { 1017pats -> headlen = 0 ; 1018 }else { 1019for (pats -> headlen = 0 ;pats -> head [pats -> headlen ]!= NUL ;pats -> headlen ++ ) { 1020if (vim_strchr (p_magic ?".[~*\\$" :"\\$" , 1021 (uint8_t )pats -> head [pats -> headlen ])!= NULL ) { 1022break ; 1023 } 1024 } 1025 } 1026if (p_tl != 0 && pats -> headlen > p_tl ) {// adjust for 'taglength' 1027pats -> headlen = (int )p_tl ; 1028 } 1029 } 1030 1031if (has_re ) { 1032pats -> regmatch .regprog = vim_regcomp (pats -> pat ,p_magic ?RE_MAGIC :0 ); 1033 }else { 1034pats -> regmatch .regprog = NULL ; 1035 } 1036} 1037 1038/// Classify "cmd" from a tagfunc result (see tagcmd_T), like a tags file 1039/// address, to decide whether a "|" terminator must be appended before storing 1040/// it in a tag line. 1041static tagcmd_T tagfunc_cmd_kind (char * cmd ) 1042{ 1043if (ascii_isdigit (* cmd )) { 1044return * skipdigits (cmd )== NUL ?TAGCMD_ADDRESS :TAGCMD_INVALID ; 1045 } 1046if (* cmd == '/' || * cmd == '?' ) { 1047// A Tab inside the pattern is fine (Universal Ctags emits one for a 1048// tab-indented line); only trailing content after the closing 1049// delimiter, which would break the tag line fields, is rejected. 1050const char * end = skip_regexp (cmd + 1 ,* cmd , false); 1051return (* end == * cmd && end [1 ]== NUL ) ?TAGCMD_ADDRESS :TAGCMD_INVALID ; 1052 } 1053if (strpbrk (cmd ,"\t\r\n" )!= NULL ) { 1054return TAGCMD_INVALID ; 1055 } 1056return TAGCMD_GENERIC ; 1057} 1058 1059/// Call the user-defined function to generate a list of tags used by 1060/// find_tags(). 1061/// 1062/// Return OK if at least 1 tag has been successfully found, 1063/// NOTDONE if the function returns v:null, and FAIL otherwise. 1064/// 1065/// @param pat pattern supplied to the user-defined function 1066/// @param ga the tags will be placed here 1067/// @param match_count here the number of tags found will be placed 1068/// @param flags flags from find_tags (TAG_*) 1069/// @param buf_ffname name of buffer for priority 1070static int find_tagfunc_tags (char * pat ,garray_T * ga ,int * match_count ,int flags ,char * buf_ffname ) 1071{ 1072int ntags = 0 ; 1073typval_T args [4 ]; 1074typval_T rettv ; 1075char flagString [4 ]; 1076taggy_T * tag = NULL ; 1077 1078if (curwin -> w_tagstacklen > 0 ) { 1079if (curwin -> w_tagstackidx == curwin -> w_tagstacklen ) { 1080tag = & curwin -> w_tagstack [curwin -> w_tagstackidx - 1 ]; 1081 }else { 1082tag = & curwin -> w_tagstack [curwin -> w_tagstackidx ]; 1083 } 1084 } 1085 1086if (curbuf -> b_p_tfu .type == kCallbackNone ) { 1087return FAIL ; 1088 } 1089 1090args [0 ].v_type = VAR_STRING ; 1091args [0 ].vval .v_string = pat ; 1092args [1 ].v_type = VAR_STRING ; 1093args [1 ].vval .v_string = flagString ; 1094 1095// create 'info' dict argument 1096dict_T * const d = tv_dict_alloc_lock (VAR_FIXED ); 1097if (!(flags & TAG_INS_COMP )&& tag != NULL && tag -> user_data != NULL ) { 1098tv_dict_add_str (d ,S_LEN ("user_data" ),tag -> user_data ); 1099 } 1100if (buf_ffname != NULL ) { 1101tv_dict_add_str (d ,S_LEN ("buf_ffname" ),buf_ffname ); 1102 } 1103 1104d -> dv_refcount ++ ; 1105args [2 ].v_type = VAR_DICT ; 1106args [2 ].vval .v_dict = d ; 1107 1108args [3 ].v_type = VAR_UNKNOWN ; 1109 1110vim_snprintf (flagString ,sizeof (flagString ), 1111"%s%s%s" , 1112g_tag_at_cursor ?"c" :"" , 1113flags & TAG_INS_COMP ?"i" :"" , 1114flags & TAG_REGEXP ?"r" :"" ); 1115 1116pos_T save_pos = curwin -> w_cursor ; 1117int result = callback_call (& curbuf -> b_p_tfu ,3 ,args ,& rettv ); 1118curwin -> w_cursor = save_pos ;// restore the cursor position 1119check_cursor (curwin );// make sure cursor position is valid 1120d -> dv_refcount -- ; 1121 1122if (result == FAIL ) { 1123return FAIL ; 1124 } 1125if (rettv .v_type == VAR_SPECIAL && rettv .vval .v_special == kSpecialVarNull ) { 1126tv_clear (& rettv ); 1127return NOTDONE ; 1128 } 1129if (rettv .v_type != VAR_LIST || !rettv .vval .v_list ) { 1130tv_clear (& rettv ); 1131emsg (_ (e_invalid_return_value_from_tagfunc )); 1132return FAIL ; 1133 } 1134list_T * taglist = rettv .vval .v_list ; 1135 1136TV_LIST_ITER_CONST (taglist ,li , { 1137char * res_name ; 1138char * res_fname ; 1139char * res_cmd ; 1140char * res_kind ; 1141bool has_extra = false; 1142int name_only = flags & TAG_NAMES ; 1143 1144if (TV_LIST_ITEM_TV (li )-> v_type != VAR_DICT ) { 1145emsg (_ (e_invalid_return_value_from_tagfunc )); 1146break ; 1147 } 1148 1149size_t len = 2 ; 1150res_name = NULL ; 1151res_fname = NULL ; 1152res_cmd = NULL ; 1153res_kind = NULL ; 1154 1155TV_DICT_ITER (TV_LIST_ITEM_TV (li )-> vval .v_dict ,di , { 1156const char * dict_key = di -> di_key ; 1157typval_T * tv = & di -> di_tv ; 1158 1159if (tv -> v_type != VAR_STRING || tv -> vval .v_string == NULL ) { 1160continue ; 1161 } 1162 1163len += strlen (tv -> vval .v_string )+ 1 ;// Space for "\tVALUE" 1164if (strcmp (dict_key ,"name" )== 0 ) { 1165res_name = tv -> vval .v_string ; 1166continue ; 1167 } 1168if (strcmp (dict_key ,"filename" )== 0 ) { 1169res_fname = tv -> vval .v_string ; 1170continue ; 1171 } 1172if (strcmp (dict_key ,"cmd" )== 0 ) { 1173res_cmd = tv -> vval .v_string ; 1174continue ; 1175 } 1176has_extra = true; 1177if (strcmp (dict_key ,"kind" )== 0 ) { 1178res_kind = tv -> vval .v_string ; 1179continue ; 1180 } 1181// Other elements will be stored as "\tKEY:VALUE" 1182// Allocate space for the key and the colon 1183len += strlen (dict_key )+ 1 ; 1184 }); 1185 1186if (has_extra ) { 1187len += 2 ;// need space for ;" 1188 } 1189 1190if (!res_name || !res_fname || !res_cmd ) { 1191emsg (_ (e_invalid_return_value_from_tagfunc )); 1192break ; 1193 } 1194 1195tagcmd_T cmdkind = tagfunc_cmd_kind (res_cmd ); 1196if (cmdkind == TAGCMD_INVALID ) { 1197emsg (_ (e_invalid_return_value_from_tagfunc )); 1198break ; 1199 } 1200if (cmdkind == TAGCMD_GENERIC ) { 1201len += 3 ;// need space for "|;\"" 1202 } 1203char * const mfp = name_only ?xstrdup (res_name ) :xmalloc (len + 2 ); 1204 1205if (!name_only ) { 1206char * p = mfp ; 1207 1208* p ++ = MT_GL_OTH + 1 ;// mtt 1209* p ++ = TAG_SEP ;// no tag file name 1210 1211STRCPY (p ,res_name ); 1212p += strlen (p ); 1213 1214* p ++ = TAB ; 1215STRCPY (p ,res_fname ); 1216p += strlen (p ); 1217 1218* p ++ = TAB ; 1219STRCPY (p ,res_cmd ); 1220p += strlen (p ); 1221 1222if (cmdkind == TAGCMD_GENERIC ) { 1223* p ++ = '|' ;// terminate the command 1224 } 1225if (cmdkind == TAGCMD_GENERIC || has_extra ) { 1226STRCPY (p ,";\"" ); 1227p += strlen (p ); 1228 1229if (res_kind ) { 1230* p ++ = TAB ; 1231STRCPY (p ,res_kind ); 1232p += strlen (p ); 1233 } 1234 1235TV_DICT_ITER (TV_LIST_ITEM_TV (li )-> vval .v_dict ,di , { 1236const char * dict_key = di -> di_key ; 1237typval_T * tv = & di -> di_tv ; 1238if (tv -> v_type != VAR_STRING || tv -> vval .v_string == NULL ) { 1239continue ; 1240 } 1241 1242if (strcmp (dict_key ,"name" )== 0 ) { 1243continue ; 1244 } 1245if (strcmp (dict_key ,"filename" )== 0 ) { 1246continue ; 1247 } 1248if (strcmp (dict_key ,"cmd" )== 0 ) { 1249continue ; 1250 } 1251if (strcmp (dict_key ,"kind" )== 0 ) { 1252continue ; 1253 } 1254 1255* p ++ = TAB ; 1256STRCPY (p ,dict_key ); 1257p += strlen (p ); 1258STRCPY (p ,":" ); 1259p += strlen (p ); 1260STRCPY (p ,tv -> vval .v_string ); 1261p += strlen (p ); 1262 }); 1263 } 1264 } 1265 1266// Add all matches because tagfunc should do filtering. 1267ga_grow (ga ,1 ); 1268 ((char ** )(ga -> ga_data ))[ga -> ga_len ++ ]= (char * )mfp ; 1269ntags ++ ; 1270result = OK ; 1271 }); 1272 1273tv_clear (& rettv ); 1274 1275* match_count = ntags ; 1276return result ; 1277} 1278 1279/// Initialize the state used by find_tags() 1280static void findtags_state_init (findtags_state_T * st ,char * pat ,int flags ,int mincount ) 1281{ 1282st -> tag_fname = xmalloc (MAXPATHL + 1 ); 1283st -> fp = NULL ; 1284st -> orgpat = xmalloc (sizeof (pat_T )); 1285st -> orgpat -> pat = pat ; 1286st -> orgpat -> len = (int )strlen (pat ); 1287st -> orgpat -> regmatch .regprog = NULL ; 1288st -> flags = flags ; 1289st -> tag_file_sorted = NUL ; 1290st -> help_lang_find = NULL ; 1291st -> is_txt = false; 1292st -> did_open = false; 1293st -> help_only = (flags & TAG_HELP ); 1294st -> get_searchpat = false; 1295st -> help_lang [0 ]= NUL ; 1296st -> help_pri = 0 ; 1297st -> mincount = mincount ; 1298st -> lbuf_size = LSIZE ; 1299st -> lbuf = xmalloc ((size_t )st -> lbuf_size ); 1300st -> match_count = 0 ; 1301st -> stop_searching = false; 1302 1303for (int mtt = 0 ;mtt < MT_COUNT ;mtt ++ ) { 1304ga_init (& st -> ga_match [mtt ],sizeof (char * ),100 ); 1305hash_init (& st -> ht_match [mtt ]); 1306 } 1307} 1308 1309/// Free the state used by find_tags() 1310static void findtags_state_free (findtags_state_T * st ) 1311{ 1312xfree (st -> tag_fname ); 1313xfree (st -> lbuf ); 1314vim_regfree (st -> orgpat -> regmatch .regprog ); 1315xfree (st -> orgpat ); 1316} 1317 1318/// Initialize the language and priority used for searching tags in a Vim help 1319/// file. 1320/// Returns true to process the help file for tags and false to skip the file. 1321static bool findtags_in_help_init (findtags_state_T * st ) 1322{ 1323int i ; 1324 1325// Keep "en" as the language if the file extension is ".txt" 1326if (st -> is_txt ) { 1327STRCPY (st -> help_lang ,"en" ); 1328 }else { 1329// Prefer help tags according to 'helplang'. Put the two-letter 1330// language name in help_lang[]. 1331i = (int )strlen (st -> tag_fname ); 1332if (i > 3 && st -> tag_fname [i - 3 ]== '-' ) { 1333xmemcpyz (st -> help_lang ,st -> tag_fname + i - 2 ,2 ); 1334 }else { 1335STRCPY (st -> help_lang ,"en" ); 1336 } 1337 } 1338// When searching for a specific language skip tags files for other 1339// languages. 1340if (st -> help_lang_find != NULL 1341&& STRICMP (st -> help_lang ,st -> help_lang_find )!= 0 ) { 1342return false; 1343 } 1344 1345// For CTRL-] in a help file prefer a match with the same language. 1346if ((st -> flags & TAG_KEEP_LANG ) 1347&& st -> help_lang_find == NULL 1348&& curbuf -> b_fname != NULL 1349&& (i = (int )strlen (curbuf -> b_fname ))> 4 1350&& curbuf -> b_fname [i - 1 ]== 'x' 1351&& curbuf -> b_fname [i - 4 ]== '.' 1352&& STRNICMP (curbuf -> b_fname + i - 3 ,st -> help_lang ,2 )== 0 ) { 1353st -> help_pri = 0 ; 1354 }else { 1355st -> help_pri = 1 ; 1356char * s ; 1357for (s = p_hlg ;* s != NUL ;s ++ ) { 1358if (STRNICMP (s ,st -> help_lang ,2 )== 0 ) { 1359break ; 1360 } 1361st -> help_pri ++ ; 1362if ((s = vim_strchr (s ,',' ))== NULL ) { 1363break ; 1364 } 1365 } 1366if (s == NULL || * s == NUL ) { 1367// Language not in 'helplang': use last, prefer English, unless 1368// found already. 1369st -> help_pri ++ ; 1370if (STRICMP (st -> help_lang ,"en" )!= 0 ) { 1371st -> help_pri ++ ; 1372 } 1373 } 1374 } 1375 1376return true; 1377} 1378 1379/// Use the function set in 'tagfunc' (if configured and enabled) to get the 1380/// tags. 1381/// Return OK if at least 1 tag has been successfully found, NOTDONE if the 1382/// 'tagfunc' is not used, still executing or the 'tagfunc' returned v:null and 1383/// FAIL otherwise. 1384static int findtags_apply_tfu (findtags_state_T * st ,char * pat ,char * buf_ffname ) 1385{ 1386const bool use_tfu = ((st -> flags & TAG_NO_TAGFUNC )== 0 ); 1387 1388if (!use_tfu || tfu_in_use || curbuf -> b_p_tfu .type == kCallbackNone ) { 1389return NOTDONE ; 1390 } 1391 1392tfu_in_use = true; 1393int retval = find_tagfunc_tags (pat ,st -> ga_match ,& st -> match_count , 1394st -> flags ,buf_ffname ); 1395tfu_in_use = false; 1396 1397return retval ; 1398} 1399 1400/// Read the next line from a tags file. 1401/// Returns TAGS_READ_SUCCESS if a tags line is successfully read and should be 1402/// processed. 1403/// Returns TAGS_READ_EOF if the end of file is reached. 1404/// Returns TAGS_READ_IGNORE if the current line should be ignored (used when 1405/// reached end of a emacs included tags file) 1406static tags_read_status_T findtags_get_next_line (findtags_state_T * st ,tagsearch_info_T * sinfo_p ) 1407{ 1408bool eof ; 1409 1410// For binary search: compute the next offset to use. 1411if (st -> state == TS_BINARY ) { 1412off_T offset = sinfo_p -> low_offset + ((sinfo_p -> high_offset - sinfo_p -> low_offset ) /2 ); 1413if (offset == sinfo_p -> curr_offset ) { 1414return TAGS_READ_EOF ;// End the binary search without a match. 1415 }else { 1416sinfo_p -> curr_offset = offset ; 1417 } 1418 }else if (st -> state == TS_SKIP_BACK ) { 1419// Skipping back (after a match during binary search). 1420sinfo_p -> curr_offset -= st -> lbuf_size * 2 ; 1421if (sinfo_p -> curr_offset < 0 ) { 1422sinfo_p -> curr_offset = 0 ; 1423fseek (st -> fp ,0 ,SEEK_SET ); 1424st -> state = TS_STEP_FORWARD ; 1425 } 1426 } 1427 1428// When jumping around in the file, first read a line to find the 1429// start of the next line. 1430if (st -> state == TS_BINARY || st -> state == TS_SKIP_BACK ) { 1431// Adjust the search file offset to the correct position 1432sinfo_p -> curr_offset_used = sinfo_p -> curr_offset ; 1433vim_ignored = vim_fseek (st -> fp ,sinfo_p -> curr_offset ,SEEK_SET ); 1434eof = vim_fgets (st -> lbuf ,st -> lbuf_size ,st -> fp ); 1435if (!eof && sinfo_p -> curr_offset != 0 ) { 1436sinfo_p -> curr_offset = vim_ftell (st -> fp ); 1437if (sinfo_p -> curr_offset == sinfo_p -> high_offset ) { 1438// oops, gone a bit too far; try from low offset 1439vim_ignored = vim_fseek (st -> fp ,sinfo_p -> low_offset ,SEEK_SET ); 1440sinfo_p -> curr_offset = sinfo_p -> low_offset ; 1441 } 1442eof = vim_fgets (st -> lbuf ,st -> lbuf_size ,st -> fp ); 1443 } 1444// skip empty and blank lines 1445while (!eof && vim_isblankline (st -> lbuf )) { 1446sinfo_p -> curr_offset = vim_ftell (st -> fp ); 1447eof = vim_fgets (st -> lbuf ,st -> lbuf_size ,st -> fp ); 1448 } 1449if (eof ) { 1450// Hit end of file. Skip backwards. 1451st -> state = TS_SKIP_BACK ; 1452sinfo_p -> match_offset = vim_ftell (st -> fp ); 1453sinfo_p -> curr_offset = sinfo_p -> curr_offset_used ; 1454return TAGS_READ_IGNORE ; 1455 } 1456 }else { 1457// Not jumping around in the file: Read the next line. 1458 1459// skip empty and blank lines 1460do { 1461eof = vim_fgets (st -> lbuf ,st -> lbuf_size ,st -> fp ); 1462 }while (!eof && vim_isblankline (st -> lbuf )); 1463 1464if (eof ) { 1465return TAGS_READ_EOF ; 1466 } 1467 } 1468 1469return TAGS_READ_SUCCESS ; 1470} 1471 1472/// Parse a tags file header line in "st->lbuf". 1473/// Returns true if the current line in st->lbuf is not a tags header line and 1474/// should be parsed as a regular tag line. Returns false if the line is a 1475/// header line and the next header line should be read. 1476static bool findtags_hdr_parse (findtags_state_T * st ) 1477{ 1478// Header lines in a tags file start with "!_TAG_" 1479if (strncmp (st -> lbuf ,"!_TAG_" ,6 )!= 0 ) { 1480// Non-header item before the header, e.g. "!" itself. 1481return true; 1482 } 1483 1484// Process the header line. 1485if (strncmp (st -> lbuf ,"!_TAG_FILE_SORTED\t" ,18 )== 0 ) { 1486st -> tag_file_sorted = (uint8_t )st -> lbuf [18 ]; 1487 } 1488if (strncmp (st -> lbuf ,"!_TAG_FILE_ENCODING\t" ,20 )== 0 ) { 1489// Prepare to convert every line from the specified encoding to 1490// 'encoding'. 1491char * p ; 1492for (p = st -> lbuf + 20 ;* p > ' ' && * p < 127 ;p ++ ) {} 1493* p = NUL ; 1494convert_setup (& st -> vimconv ,st -> lbuf + 20 ,p_enc ); 1495 } 1496 1497// Read the next line. Unrecognized flags are ignored. 1498return false; 1499} 1500 1501/// Handler to initialize the state when starting to process a new tags file. 1502/// Called in the TS_START state when finding tags from a tags file. 1503/// Returns true if the line read from the tags file should be parsed and 1504/// false if the line should be ignored. 1505static bool findtags_start_state_handler (findtags_state_T * st ,bool * sortic , 1506tagsearch_info_T * sinfo_p ) 1507{ 1508const bool noic = (st -> flags & TAG_NOIC ); 1509 1510// The header ends when the line sorts below "!_TAG_". When case is 1511// folded lower case letters sort before "_". 1512if (strncmp (st -> lbuf ,"!_TAG_" ,6 ) <=0 1513|| (st -> lbuf [0 ]== '!' && ASCII_ISLOWER (st -> lbuf [1 ]))) { 1514return findtags_hdr_parse (st ); 1515 } 1516 1517// Headers ends. 1518 1519// When there is no tag head, or ignoring case, need to do a 1520// linear search. 1521// When no "!_TAG_" is found, default to binary search. If 1522// the tag file isn't sorted, the second loop will find it. 1523// When "!_TAG_FILE_SORTED" found: start binary search if 1524// flag set. 1525if (st -> linear ) { 1526st -> state = TS_LINEAR ; 1527 }else if (st -> tag_file_sorted == NUL ) { 1528st -> state = TS_BINARY ; 1529 }else if (st -> tag_file_sorted == '1' ) { 1530st -> state = TS_BINARY ; 1531 }else if (st -> tag_file_sorted == '2' ) { 1532st -> state = TS_BINARY ; 1533* sortic = true; 1534st -> orgpat -> regmatch .rm_ic = (p_ic || !noic ); 1535 }else { 1536st -> state = TS_LINEAR ; 1537 } 1538 1539if (st -> state == TS_BINARY && st -> orgpat -> regmatch .rm_ic && !* sortic ) { 1540// Binary search won't work for ignoring case, use linear 1541// search. 1542st -> linear = true; 1543st -> state = TS_LINEAR ; 1544 } 1545 1546// When starting a binary search, get the size of the file and 1547// compute the first offset. 1548if (st -> state == TS_BINARY ) { 1549if (vim_fseek (st -> fp ,0 ,SEEK_END )!= 0 ) { 1550// can't seek, don't use binary search 1551st -> state = TS_LINEAR ; 1552 }else { 1553// Get the tag file size. 1554// Don't use lseek(), it doesn't work 1555// properly on MacOS Catalina. 1556const off_T filesize = vim_ftell (st -> fp ); 1557vim_ignored = vim_fseek (st -> fp ,0 ,SEEK_SET ); 1558 1559// Calculate the first read offset in the file. Start 1560// the search in the middle of the file. 1561sinfo_p -> low_offset = 0 ; 1562sinfo_p -> low_char = 0 ; 1563sinfo_p -> high_offset = filesize ; 1564sinfo_p -> curr_offset = 0 ; 1565sinfo_p -> high_char = 0xff ; 1566 } 1567return false; 1568 } 1569 1570return true; 1571} 1572 1573/// Parse a tag line read from a tags file. 1574/// Also compares the tag name in "tagpp->tagname" with a search pattern in 1575/// "st->orgpat->head" as a quick check if the tag may match. 1576/// Returns: 1577/// - TAG_MATCH_SUCCESS if the tag may match 1578/// - TAG_MATCH_FAIL if the tag doesn't match 1579/// - TAG_MATCH_NEXT to look for the next matching tag (used in a binary search) 1580/// - TAG_MATCH_STOP if all the tags are processed without a match. 1581/// Uses the values in "margs" for doing the comparison. 1582static tagmatch_status_T findtags_parse_line (findtags_state_T * st ,tagptrs_T * tagpp , 1583findtags_match_args_T * margs , 1584tagsearch_info_T * sinfo_p ) 1585{ 1586int status ; 1587 1588// Figure out where the different strings are in this line. 1589// For "normal" tags: Do a quick check if the tag matches. 1590// This speeds up tag searching a lot! 1591if (st -> orgpat -> headlen ) { 1592CLEAR_FIELD (* tagpp ); 1593tagpp -> tagname = st -> lbuf ; 1594tagpp -> tagname_end = vim_strchr (st -> lbuf ,TAB ); 1595if (tagpp -> tagname_end == NULL ) { 1596// Corrupted tag line. 1597return TAG_MATCH_FAIL ; 1598 } 1599 1600// Skip this line if the length of the tag is different and 1601// there is no regexp, or the tag is too short. 1602int cmplen = (int )(tagpp -> tagname_end - tagpp -> tagname ); 1603if (p_tl != 0 && cmplen > p_tl ) {// adjust for 'taglength' 1604cmplen = (int )p_tl ; 1605 } 1606if ((st -> flags & TAG_REGEXP )&& st -> orgpat -> headlen < cmplen ) { 1607cmplen = st -> orgpat -> headlen ; 1608 }else if (st -> state == TS_LINEAR && st -> orgpat -> headlen != cmplen ) { 1609return TAG_MATCH_NEXT ; 1610 } 1611 1612if (st -> state == TS_BINARY ) { 1613int tagcmp ; 1614// Simplistic check for unsorted tags file. 1615int i = (uint8_t )tagpp -> tagname [0 ]; 1616if (margs -> sortic ) { 1617i = TOUPPER_ASC (tagpp -> tagname [0 ]); 1618 } 1619if (i < sinfo_p -> low_char || i > sinfo_p -> high_char ) { 1620margs -> sort_error = true; 1621 } 1622 1623// Compare the current tag with the searched tag. 1624if (margs -> sortic ) { 1625tagcmp = tag_strnicmp (tagpp -> tagname ,st -> orgpat -> head , 1626 (size_t )cmplen ); 1627 }else { 1628tagcmp = strncmp (tagpp -> tagname ,st -> orgpat -> head , (size_t )cmplen ); 1629 } 1630 1631// A match with a shorter tag means to search forward. 1632// A match with a longer tag means to search backward. 1633if (tagcmp == 0 ) { 1634if (cmplen < st -> orgpat -> headlen ) { 1635tagcmp = -1 ; 1636 }else if (cmplen > st -> orgpat -> headlen ) { 1637tagcmp = 1 ; 1638 } 1639 } 1640 1641if (tagcmp == 0 ) { 1642// We've located the tag, now skip back and search 1643// forward until the first matching tag is found. 1644st -> state = TS_SKIP_BACK ; 1645sinfo_p -> match_offset = sinfo_p -> curr_offset ; 1646return TAG_MATCH_NEXT ; 1647 } 1648if (tagcmp < 0 ) { 1649sinfo_p -> curr_offset = vim_ftell (st -> fp ); 1650if (sinfo_p -> curr_offset < sinfo_p -> high_offset ) { 1651sinfo_p -> low_offset = sinfo_p -> curr_offset ; 1652if (margs -> sortic ) { 1653sinfo_p -> low_char = TOUPPER_ASC (tagpp -> tagname [0 ]); 1654 }else { 1655sinfo_p -> low_char = (uint8_t )tagpp -> tagname [0 ]; 1656 } 1657return TAG_MATCH_NEXT ; 1658 } 1659 } 1660if (tagcmp > 0 && sinfo_p -> curr_offset != sinfo_p -> high_offset ) { 1661sinfo_p -> high_offset = sinfo_p -> curr_offset ; 1662if (margs -> sortic ) { 1663sinfo_p -> high_char = TOUPPER_ASC (tagpp -> tagname [0 ]); 1664 }else { 1665sinfo_p -> high_char = (uint8_t )tagpp -> tagname [0 ]; 1666 } 1667return TAG_MATCH_NEXT ; 1668 } 1669 1670// No match yet and are at the end of the binary search. 1671return TAG_MATCH_STOP ; 1672 }else if (st -> state == TS_SKIP_BACK ) { 1673assert (cmplen >=0 ); 1674if (mb_strnicmp (tagpp -> tagname ,st -> orgpat -> head , (size_t )cmplen )!= 0 ) { 1675st -> state = TS_STEP_FORWARD ; 1676 }else { 1677// Have to skip back more. Restore the curr_offset 1678// used, otherwise we get stuck at a long line. 1679sinfo_p -> curr_offset = sinfo_p -> curr_offset_used ; 1680 } 1681return TAG_MATCH_NEXT ; 1682 }else if (st -> state == TS_STEP_FORWARD ) { 1683assert (cmplen >=0 ); 1684if (mb_strnicmp (tagpp -> tagname ,st -> orgpat -> head , (size_t )cmplen )!= 0 ) { 1685return ((off_T )vim_ftell (st -> fp )> sinfo_p -> match_offset ) 1686 ?TAG_MATCH_STOP // past last match 1687 :TAG_MATCH_NEXT ;// before first match 1688 } 1689 }else { 1690// skip this match if it can't match 1691assert (cmplen >=0 ); 1692if (mb_strnicmp (tagpp -> tagname ,st -> orgpat -> head , (size_t )cmplen )!= 0 ) { 1693return TAG_MATCH_NEXT ; 1694 } 1695 } 1696 1697// Can be a matching tag, isolate the file name and command. 1698tagpp -> fname = tagpp -> tagname_end + 1 ; 1699tagpp -> fname_end = vim_strchr (tagpp -> fname ,TAB ); 1700if (tagpp -> fname_end == NULL ) { 1701status = FAIL ; 1702 }else { 1703tagpp -> command = tagpp -> fname_end + 1 ; 1704status = OK ; 1705 } 1706 }else { 1707status = parse_tag_line (st -> lbuf ,tagpp ); 1708 } 1709 1710return status == FAIL 1711 ?TAG_MATCH_FAIL 1712 :TAG_MATCH_SUCCESS ; 1713} 1714 1715/// Initialize the structure used for tag matching. 1716static void findtags_matchargs_init (findtags_match_args_T * margs ,int flags ) 1717{ 1718margs -> matchoff = 0 ;// match offset 1719margs -> match_re = false;// match with regexp 1720margs -> match_no_ic = false;// matches with case 1721margs -> has_re = (flags & TAG_REGEXP );// regexp used 1722margs -> sortic = false;// tag file sorted in nocase 1723margs -> sort_error = false;// tags file not sorted 1724} 1725 1726/// Compares the tag name in "tagpp->tagname" with a search pattern in 1727/// "st->orgpat->pat". 1728/// Returns true if the tag matches, false if the tag doesn't match. 1729/// Uses the values in "margs" for doing the comparison. 1730static bool findtags_match_tag (findtags_state_T * st ,tagptrs_T * tagpp ,findtags_match_args_T * margs ) 1731{ 1732bool match = false; 1733 1734// First try matching with the pattern literally (also when it is 1735// a regexp). 1736int cmplen = (int )(tagpp -> tagname_end - tagpp -> tagname ); 1737if (p_tl != 0 && cmplen > p_tl ) {// adjust for 'taglength' 1738cmplen = (int )p_tl ; 1739 } 1740// if tag length does not match, don't try comparing 1741if (st -> orgpat -> len != cmplen ) { 1742match = false; 1743 }else { 1744if (st -> orgpat -> regmatch .rm_ic ) { 1745assert (cmplen >=0 ); 1746match = mb_strnicmp (tagpp -> tagname ,st -> orgpat -> pat , (size_t )cmplen )== 0 ; 1747if (match ) { 1748margs -> match_no_ic = strncmp (tagpp -> tagname ,st -> orgpat -> pat , (size_t )cmplen )== 0 ; 1749 } 1750 }else { 1751match = strncmp (tagpp -> tagname ,st -> orgpat -> pat , (size_t )cmplen )== 0 ; 1752 } 1753 } 1754 1755// Has a regexp: Also find tags matching regexp. 1756margs -> match_re = false; 1757if (!match && st -> orgpat -> regmatch .regprog != NULL ) { 1758char cc = * tagpp -> tagname_end ; 1759* tagpp -> tagname_end = NUL ; 1760match = vim_regexec (& st -> orgpat -> regmatch ,tagpp -> tagname ,0 ); 1761if (match ) { 1762margs -> matchoff = (int )(st -> orgpat -> regmatch .startp [0 ]- tagpp -> tagname ); 1763if (st -> orgpat -> regmatch .rm_ic ) { 1764st -> orgpat -> regmatch .rm_ic = false; 1765margs -> match_no_ic = vim_regexec (& st -> orgpat -> regmatch , 1766tagpp -> tagname ,0 ); 1767st -> orgpat -> regmatch .rm_ic = true; 1768 } 1769 } 1770* tagpp -> tagname_end = cc ; 1771margs -> match_re = true; 1772 } 1773 1774return match ; 1775} 1776 1777/// Convert the encoding of a line read from a tags file in "st->lbuf". 1778/// Converting the pattern from 'enc' to the tags file encoding doesn't work, 1779/// because characters are not recognized. The converted line is saved in 1780/// st->lbuf. 1781static void findtags_string_convert (findtags_state_T * st ) 1782{ 1783char * conv_line = string_convert (& st -> vimconv ,st -> lbuf ,NULL ); 1784if (conv_line == NULL ) { 1785return ; 1786 } 1787 1788// Copy or swap lbuf and conv_line. 1789int len = (int )strlen (conv_line )+ 1 ; 1790if (len > st -> lbuf_size ) { 1791xfree (st -> lbuf ); 1792st -> lbuf = conv_line ; 1793st -> lbuf_size = len ; 1794 }else { 1795STRCPY (st -> lbuf ,conv_line ); 1796xfree (conv_line ); 1797 } 1798} 1799 1800/// Add a matching tag found in a tags file to st->ht_match and st->ga_match. 1801static void findtags_add_match (findtags_state_T * st ,tagptrs_T * tagpp ,findtags_match_args_T * margs , 1802char * buf_ffname ,hash_T * hash ) 1803{ 1804const bool name_only = (st -> flags & TAG_NAMES ); 1805size_t len = 0 ; 1806size_t mfp_size = 0 ; 1807char * mfp ; 1808 1809// Decide in which array to store this match. 1810bool is_current = test_for_current (tagpp -> fname ,tagpp -> fname_end , 1811st -> tag_fname ,buf_ffname ); 1812 1813// current tag line is static 1814bool is_static = test_for_static (tagpp ); 1815 1816// Decide in which of the sixteen tables to store this match. 1817int mtt = is_static 1818 ?is_current ?MT_ST_CUR :MT_ST_OTH 1819 :is_current ?MT_GL_CUR :MT_GL_OTH ; 1820 1821if (st -> orgpat -> regmatch .rm_ic && !margs -> match_no_ic ) { 1822mtt += MT_IC_OFF ; 1823 } 1824if (margs -> match_re ) { 1825mtt += MT_RE_OFF ; 1826 } 1827 1828// Add the found match in ht_match[mtt] and ga_match[mtt]. 1829// Store the info we need later, which depends on the kind of 1830// tags we are dealing with. 1831if (st -> help_only ) { 1832#define ML_EXTRA 3 1833// Append the help-heuristic number after the tagname, for 1834// sorting it later. The heuristic is ignored for 1835// detecting duplicates. 1836// The format is {tagname}@{lang}NUL{heuristic}NUL 1837* tagpp -> tagname_end = NUL ; 1838len = (size_t )(tagpp -> tagname_end - tagpp -> tagname ); 1839mfp_size = sizeof (char )+ len + 10 + ML_EXTRA + 1 ; 1840mfp = xmalloc (mfp_size ); 1841 1842char * p = mfp ; 1843STRCPY (p ,tagpp -> tagname ); 1844p [len ]= '@' ; 1845STRCPY (p + len + 1 ,st -> help_lang ); 1846snprintf (p + len + 1 + ML_EXTRA ,mfp_size - (len + 1 + ML_EXTRA ),"%06d" , 1847help_heuristic (tagpp -> tagname , 1848margs -> match_re ?margs -> matchoff :0 , 1849 !margs -> match_no_ic )+ st -> help_pri ); 1850 1851* tagpp -> tagname_end = TAB ; 1852 }else if (name_only ) { 1853if (st -> get_searchpat ) { 1854char * temp_end = tagpp -> command ; 1855 1856if (* temp_end == '/' ) { 1857while (* temp_end && * temp_end != '\r' 1858&& * temp_end != '\n' 1859&& * temp_end != '$' ) { 1860temp_end ++ ; 1861 } 1862 } 1863 1864if (tagpp -> command + 2 < temp_end ) { 1865len = (size_t )(temp_end - tagpp -> command - 2 ); 1866mfp = xmalloc (len + 2 ); 1867xmemcpyz (mfp ,tagpp -> command + 2 ,len ); 1868 }else { 1869mfp = NULL ; 1870 } 1871st -> get_searchpat = false; 1872 }else { 1873len = (size_t )(tagpp -> tagname_end - tagpp -> tagname ); 1874mfp = xmalloc (sizeof (char )+ len + 1 ); 1875xmemcpyz (mfp ,tagpp -> tagname ,len ); 1876 1877// if wanted, re-read line to get long form too 1878if (State & MODE_INSERT ) { 1879st -> get_searchpat = p_sft ; 1880 } 1881 } 1882 }else { 1883size_t tag_fname_len = strlen (st -> tag_fname ); 1884// Save the tag in a buffer. 1885// Use 0x02 to separate fields (Can't use NUL, because the 1886// hash key is terminated by NUL). 1887// Emacs tag: <mtt><tag_fname><0x02><ebuf><0x02><lbuf><NUL> 1888// other tag: <mtt><tag_fname><0x02><0x02><lbuf><NUL> 1889// without Emacs tags: <mtt><tag_fname><0x02><lbuf><NUL> 1890// Here <mtt> is the "mtt" value plus 1 to avoid NUL. 1891len = tag_fname_len + strlen (st -> lbuf )+ 3 ; 1892mfp = xmalloc (sizeof (char )+ len + 1 ); 1893char * p = mfp ; 1894p [0 ]= (char )(mtt + 1 ); 1895STRCPY (p + 1 ,st -> tag_fname ); 1896p [tag_fname_len + 1 ]= TAG_SEP ; 1897char * s = p + 1 + tag_fname_len + 1 ; 1898STRCPY (s ,st -> lbuf ); 1899 } 1900 1901if (mfp != NULL ) { 1902hashitem_T * hi ; 1903 1904// Don't add identical matches. 1905// "mfp" is used as a hash key, there is a NUL byte to end 1906// the part that matters for comparing, more bytes may 1907// follow after it. E.g. help tags store the priority 1908// after the NUL. 1909* hash = hash_hash (mfp ); 1910hi = hash_lookup (& st -> ht_match [mtt ],mfp ,strlen (mfp ),* hash ); 1911if (HASHITEM_EMPTY (hi )) { 1912hash_add_item (& st -> ht_match [mtt ],hi ,mfp ,* hash ); 1913GA_APPEND (char * ,& st -> ga_match [mtt ],mfp ); 1914st -> match_count ++ ; 1915 }else { 1916// duplicate tag, drop it 1917xfree (mfp ); 1918 } 1919 } 1920} 1921 1922/// Read and get all the tags from file st->tag_fname. 1923/// Sets "st->stop_searching" to true to stop searching for additional tags. 1924static void findtags_get_all_tags (findtags_state_T * st ,findtags_match_args_T * margs , 1925char * buf_ffname ) 1926{ 1927tagptrs_T tagp ; 1928tagsearch_info_T search_info ; 1929hash_T hash = 0 ; 1930 1931// This is only to avoid a compiler warning for using search_info 1932// uninitialised. 1933CLEAR_FIELD (search_info ); 1934 1935// Read and parse the lines in the file one by one 1936while (true) { 1937// check for CTRL-C typed, more often when jumping around 1938if (st -> state == TS_BINARY || st -> state == TS_SKIP_BACK ) { 1939line_breakcheck (); 1940 }else { 1941fast_breakcheck (); 1942 } 1943if ((st -> flags & TAG_INS_COMP )) {// Double brackets for gcc 1944ins_compl_check_keys (30 , false); 1945 } 1946if (got_int || ins_compl_interrupted ()) { 1947st -> stop_searching = true; 1948break ; 1949 } 1950// When mincount is TAG_MANY, stop when enough matches have been 1951// found (for completion). 1952if (st -> mincount == TAG_MANY && st -> match_count >=TAG_MANY ) { 1953st -> stop_searching = true; 1954break ; 1955 } 1956if (st -> get_searchpat ) { 1957 gotoline_read_in ; 1958 } 1959 1960int retval = (int )findtags_get_next_line (st ,& search_info ); 1961if (retval == TAGS_READ_IGNORE ) { 1962continue ; 1963 } 1964if (retval == TAGS_READ_EOF ) { 1965break ; 1966 } 1967 1968line_read_in : 1969 1970if (st -> vimconv .vc_type != CONV_NONE ) { 1971findtags_string_convert (st ); 1972 } 1973 1974// When still at the start of the file, check for Emacs tags file 1975// format, and for "not sorted" flag. 1976if (st -> state == TS_START ) { 1977if (!findtags_start_state_handler (st ,& margs -> sortic ,& search_info )) { 1978continue ; 1979 } 1980 } 1981 1982// When the line is too long the NUL will not be in the 1983// last-but-one byte (see vim_fgets()). 1984// Has been reported for Mozilla JS with extremely long names. 1985// In that case we need to increase lbuf_size. 1986if (st -> lbuf [st -> lbuf_size - 2 ]!= NUL ) { 1987st -> lbuf_size *=2 ; 1988xfree (st -> lbuf ); 1989st -> lbuf = xmalloc ((size_t )st -> lbuf_size ); 1990 1991if (st -> state == TS_STEP_FORWARD || st -> state == TS_LINEAR ) { 1992// Seek to the same position to read the same line again 1993vim_ignored = vim_fseek (st -> fp ,search_info .curr_offset ,SEEK_SET ); 1994 } 1995// this will try the same thing again, make sure the offset is 1996// different 1997search_info .curr_offset = 0 ; 1998continue ; 1999 } 2000 2001retval = (int )findtags_parse_line (st ,& tagp ,margs ,& search_info ); 2002if (retval == TAG_MATCH_NEXT ) { 2003continue ; 2004 } 2005if (retval == TAG_MATCH_STOP ) { 2006break ; 2007 } 2008if (retval == TAG_MATCH_FAIL ) { 2009semsg (_ ("E431: Format error in tags file \"%s\"" ),st -> tag_fname ); 2010semsg (_ ("Before byte %" PRId64 ), (int64_t )vim_ftell (st -> fp )); 2011st -> stop_searching = true; 2012return ; 2013 } 2014 2015// If a match is found, add it to ht_match[] and ga_match[]. 2016if (findtags_match_tag (st ,& tagp ,margs )) { 2017findtags_add_match (st ,& tagp ,margs ,buf_ffname ,& hash ); 2018 } 2019 }// forever 2020} 2021 2022/// Search for tags matching "st->orgpat.pat" in the "st->tag_fname" tags file. 2023/// Information needed to search for the tags is in the "st" state structure. 2024/// The matching tags are returned in "st". If an error is encountered, then 2025/// "st->stop_searching" is set to true. 2026static void findtags_in_file (findtags_state_T * st ,int flags ,char * buf_ffname ) 2027{ 2028findtags_match_args_T margs ; 2029 2030st -> vimconv .vc_type = CONV_NONE ; 2031st -> tag_file_sorted = NUL ; 2032st -> fp = NULL ; 2033findtags_matchargs_init (& margs ,st -> flags ); 2034 2035// A file that doesn't exist is silently ignored. Only when not a 2036// single file is found, an error message is given (further on). 2037if (curbuf -> b_help ) { 2038if (!findtags_in_help_init (st )) { 2039return ; 2040 } 2041 } 2042 2043st -> fp = os_fopen (st -> tag_fname ,"r" ); 2044if (st -> fp == NULL ) { 2045return ; 2046 } 2047 2048if (p_verbose >=5 ) { 2049verbose_enter (); 2050smsg (0 ,_ ("Searching tags file %s" ),st -> tag_fname ); 2051verbose_leave (); 2052 } 2053st -> did_open = true;// remember that we found at least one file 2054 2055st -> state = TS_START ;// we're at the start of the file 2056 2057// Read and parse the lines in the file one by one 2058findtags_get_all_tags (st ,& margs ,buf_ffname ); 2059 2060if (st -> fp != NULL ) { 2061fclose (st -> fp ); 2062st -> fp = NULL ; 2063 } 2064if (st -> vimconv .vc_type != CONV_NONE ) { 2065convert_setup (& st -> vimconv ,NULL ,NULL ); 2066 } 2067 2068if (margs .sort_error ) { 2069semsg (_ ("E432: Tags file not sorted: %s" ),st -> tag_fname ); 2070 } 2071 2072// Stop searching if sufficient tags have been found. 2073if (st -> match_count >=st -> mincount ) { 2074st -> stop_searching = true; 2075 } 2076} 2077 2078/// Copy the tags found by find_tags() to "matchesp". 2079/// Returns the number of matches copied. 2080static int findtags_copy_matches (findtags_state_T * st ,char *** matchesp ) 2081{ 2082const bool name_only = (st -> flags & TAG_NAMES ); 2083 2084char ** matches = st -> match_count > 0 2085 ?xmalloc ((size_t )st -> match_count * sizeof (char * )) 2086 :NULL ; 2087 2088st -> match_count = 0 ; 2089for (int mtt = 0 ;mtt < MT_COUNT ;mtt ++ ) { 2090for (int i = 0 ;i < st -> ga_match [mtt ].ga_len ;i ++ ) { 2091char * mfp = ((char ** )(st -> ga_match [mtt ].ga_data ))[i ]; 2092if (matches == NULL ) { 2093xfree (mfp ); 2094 }else { 2095if (!name_only ) { 2096// Change mtt back to zero-based. 2097* mfp = (char )(* mfp - 1 ); 2098 2099// change the TAG_SEP back to NUL 2100for (char * p = mfp + 1 ;* p != NUL ;p ++ ) { 2101if (* p == TAG_SEP ) { 2102* p = NUL ; 2103 } 2104 } 2105 } 2106matches [st -> match_count ++ ]= mfp ; 2107 } 2108 } 2109 2110ga_clear (& st -> ga_match [mtt ]); 2111hash_clear (& st -> ht_match [mtt ]); 2112 } 2113 2114* matchesp = matches ; 2115return st -> match_count ; 2116} 2117 2118/// find_tags() - search for tags in tags files 2119/// 2120/// Return FAIL if search completely failed (*num_matches will be 0, *matchesp 2121/// will be NULL), OK otherwise. 2122/// 2123/// There is a priority in which type of tag is recognized. 2124/// 2125/// 6. A static or global tag with a full matching tag for the current file. 2126/// 5. A global tag with a full matching tag for another file. 2127/// 4. A static tag with a full matching tag for another file. 2128/// 3. A static or global tag with an ignore-case matching tag for the 2129/// current file. 2130/// 2. A global tag with an ignore-case matching tag for another file. 2131/// 1. A static tag with an ignore-case matching tag for another file. 2132/// 2133/// Tags in an emacs-style tags file are always global. 2134/// 2135/// flags: 2136/// TAG_HELP only search for help tags 2137/// TAG_NAMES only return name of tag 2138/// TAG_REGEXP use "pat" as a regexp 2139/// TAG_NOIC don't always ignore case 2140/// TAG_KEEP_LANG keep language 2141/// TAG_NO_TAGFUNC do not call the 'tagfunc' function 2142/// 2143/// @param pat pattern to search for 2144/// @param num_matches return: number of matches found 2145/// @param matchesp return: array of matches found 2146/// @param mincount MAXCOL: find all matches 2147/// other: minimal number of matches 2148/// @param buf_ffname name of buffer for priority 2149int find_tags (char * pat ,int * num_matches ,char *** matchesp ,int flags ,int mincount , 2150char * buf_ffname ) 2151{ 2152findtags_state_T st ; 2153tagname_T tn ;// info for get_tagfname() 2154int first_file ;// trying first tag file 2155int retval = FAIL ;// return value 2156 2157int i ; 2158char * saved_pat = NULL ;// copy of pat[] 2159 2160int findall = (mincount == MAXCOL || mincount == TAG_MANY );// find all matching tags 2161bool has_re = (flags & TAG_REGEXP );// regexp used 2162int noic = (flags & TAG_NOIC ); 2163int verbose = (flags & TAG_VERBOSE ); 2164int save_p_ic = p_ic ; 2165 2166// uncrustify:off 2167 2168// Change the value of 'ignorecase' according to 'tagcase' for the 2169// duration of this function. 2170switch (curbuf -> b_tc_flags ?curbuf -> b_tc_flags :tc_flags ) { 2171case kOptTcFlagFollowic :break ; 2172case kOptTcFlagIgnore : 2173p_ic = true; 2174break ; 2175case kOptTcFlagMatch : 2176p_ic = false; 2177break ; 2178case kOptTcFlagFollowscs : 2179p_ic = ignorecase (pat ); 2180break ; 2181case kOptTcFlagSmart : 2182p_ic = ignorecase_opt (pat , true, true); 2183break ; 2184default : 2185abort (); 2186 } 2187 2188// uncrustify:on 2189 2190const bool help_save = curbuf -> b_help ; 2191 2192findtags_state_init (& st ,pat ,flags ,mincount ); 2193 2194// Initialize a few variables 2195if (st .help_only ) {// want tags from help file 2196curbuf -> b_help = true;// will be restored later 2197 } 2198 2199if (curbuf -> b_help ) { 2200// When "@ab" is specified use only the "ab" language, otherwise 2201// search all languages. 2202if (st .orgpat -> len > 3 && pat [st .orgpat -> len - 3 ]== '@' 2203&& ASCII_ISALPHA (pat [st .orgpat -> len - 2 ]) 2204&& ASCII_ISALPHA (pat [st .orgpat -> len - 1 ])) { 2205saved_pat = xstrnsave (pat , (size_t )st .orgpat -> len - 3 ); 2206st .help_lang_find = & pat [st .orgpat -> len - 2 ]; 2207st .orgpat -> pat = saved_pat ; 2208st .orgpat -> len -= 3 ; 2209 } 2210 } 2211if (p_tl != 0 && st .orgpat -> len > p_tl ) {// adjust for 'taglength' 2212st .orgpat -> len = (int )p_tl ; 2213 } 2214 2215int save_emsg_off = emsg_off ; 2216emsg_off = true;// don't want error for invalid RE here 2217prepare_pats (st .orgpat ,has_re ); 2218emsg_off = save_emsg_off ; 2219if (has_re && st .orgpat -> regmatch .regprog == NULL ) { 2220 gotofindtag_end ; 2221 } 2222 2223retval = findtags_apply_tfu (& st ,pat ,buf_ffname ); 2224if (retval != NOTDONE ) { 2225 gotofindtag_end ; 2226 } 2227 2228// re-initialize the default return value 2229retval = FAIL ; 2230 2231// Set a flag if the file extension is .txt 2232if ((flags & TAG_KEEP_LANG ) 2233&& st .help_lang_find == NULL 2234&& curbuf -> b_fname != NULL 2235&& (i = (int )strlen (curbuf -> b_fname ))> 4 2236&& STRICMP (curbuf -> b_fname + i - 4 ,".txt" )== 0 ) { 2237st .is_txt = true; 2238 } 2239 2240// When finding a specified number of matches, first try with matching 2241// case, so binary search can be used, and try ignore-case matches in a 2242// second loop. 2243// When finding all matches, 'tagbsearch' is off, or there is no fixed 2244// string to look for, ignore case right away to avoid going though the 2245// tags files twice. 2246// When the tag file is case-fold sorted, it is either one or the other. 2247// Only ignore case when TAG_NOIC not used or 'ignorecase' set. 2248st .orgpat -> regmatch .rm_ic = ((p_ic || !noic ) 2249&& (findall || st .orgpat -> headlen == 0 || !p_tbs )); 2250for (int round = 1 ;round <=2 ;round ++ ) { 2251st .linear = (st .orgpat -> headlen == 0 || !p_tbs || round == 2 ); 2252 2253// Try tag file names from tags option one by one. 2254for (first_file = true; 2255get_tagfname (& tn ,first_file ,st .tag_fname )== OK ; 2256first_file = false) { 2257findtags_in_file (& st ,flags ,buf_ffname ); 2258if (st .stop_searching ) { 2259retval = OK ; 2260break ; 2261 } 2262 }// end of for-each-file loop 2263 2264tagname_free (& tn ); 2265 2266// stop searching when already did a linear search, or when TAG_NOIC 2267// used, and 'ignorecase' not set or already did case-ignore search 2268if (st .stop_searching || st .linear || (!p_ic && noic ) 2269|| st .orgpat -> regmatch .rm_ic ) { 2270break ; 2271 } 2272 2273// try another time while ignoring case 2274st .orgpat -> regmatch .rm_ic = true; 2275 } 2276 2277if (!st .stop_searching ) { 2278if (!st .did_open && verbose ) {// never opened any tags file 2279emsg (_ ("E433: No tags file" )); 2280 } 2281retval = OK ;// It's OK even when no tag found 2282 } 2283 2284findtag_end : 2285findtags_state_free (& st ); 2286 2287// Move the matches from the ga_match[] arrays into one list of 2288// matches. When retval == FAIL, free the matches. 2289if (retval == FAIL ) { 2290st .match_count = 0 ; 2291 } 2292 2293* num_matches = findtags_copy_matches (& st ,matchesp ); 2294 2295curbuf -> b_help = help_save ; 2296xfree (saved_pat ); 2297 2298p_ic = save_p_ic ; 2299 2300return retval ; 2301} 2302 2303static garray_T tag_fnames = GA_EMPTY_INIT_VALUE ; 2304 2305// Callback function for finding all "tags" and "tags-??" files in 2306// 'runtimepath' doc directories. 2307static bool found_tagfile_cb (int num_fnames ,char ** fnames ,bool all ,void * cookie ) 2308{ 2309for (int i = 0 ;i < num_fnames ;i ++ ) { 2310char * const tag_fname = xstrdup (fnames [i ]); 2311 2312simplify_filename (tag_fname ); 2313GA_APPEND (char * ,& tag_fnames ,tag_fname ); 2314 2315if (!all ) { 2316break ; 2317 } 2318 } 2319 2320return num_fnames > 0 ; 2321} 2322 2323#ifdef EXITFREE 2324void free_tag_stuff (void ) 2325{ 2326ga_clear_strings (& tag_fnames ); 2327if (curwin != NULL ) { 2328do_tag (NULL ,NULL ,DT_FREE ,0 ,0 ,0 ); 2329 } 2330tag_freematch (); 2331 2332tagstack_clear_entry (& ptag_entry ); 2333} 2334 2335#endif 2336 2337/// Get the next name of a tag file from the tag file list. 2338/// For help files, use "tags" file only. 2339/// 2340/// @param tnp holds status info 2341/// @param first true when first file name is wanted 2342/// @param buf pointer to buffer of MAXPATHL chars 2343/// 2344/// @return FAIL if no more tag file names, OK otherwise. 2345int get_tagfname (tagname_T * tnp ,int first ,char * buf ) 2346{ 2347char * fname = NULL ; 2348 2349if (first ) { 2350CLEAR_POINTER (tnp ); 2351 } 2352 2353if (curbuf -> b_help ) { 2354// For help files it's done in a completely different way: 2355// Find "doc/tags" and "doc/tags-??" in all directories in 2356// 'runtimepath'. 2357if (first ) { 2358ga_clear_strings (& tag_fnames ); 2359ga_init (& tag_fnames , (int )sizeof (char * ),10 ); 2360do_in_runtimepath ("doc/tags doc/tags-??" ,DIP_ALL , 2361found_tagfile_cb ,NULL ); 2362 } 2363 2364if (tnp -> tn_hf_idx >=tag_fnames .ga_len ) { 2365// Not found in 'runtimepath', use 'helpfile', if it exists and 2366// wasn't used yet, replacing "help.txt" with "tags". 2367if (tnp -> tn_hf_idx > tag_fnames .ga_len || * p_hf == NUL ) { 2368return FAIL ; 2369 } 2370tnp -> tn_hf_idx ++ ; 2371xstrlcpy (buf ,p_hf ,MAXPATHL - STRLEN_LITERAL ("tags" )); 2372STRCPY (path_tail (buf ),"tags" ); 2373simplify_filename (buf ); 2374 2375for (int i = 0 ;i < tag_fnames .ga_len ;i ++ ) { 2376if (strcmp (buf , ((char ** )(tag_fnames .ga_data ))[i ])== 0 ) { 2377return FAIL ;// avoid duplicate file names 2378 } 2379 } 2380 }else { 2381xstrlcpy (buf , ((char ** )(tag_fnames .ga_data ))[tnp -> tn_hf_idx ++ ],MAXPATHL ); 2382 } 2383return OK ; 2384 } 2385 2386if (first ) { 2387// Init. We make a copy of 'tags', because autocommands may change 2388// the value without notifying us. 2389tnp -> tn_tags = xstrdup ((* curbuf -> b_p_tags != NUL ) ?curbuf -> b_p_tags :p_tags ); 2390tnp -> tn_np = tnp -> tn_tags ; 2391 } 2392 2393// Loop until we have found a file name that can be used. 2394// There are two states: 2395// tnp->tn_did_filefind_init == false: setup for next part in 'tags'. 2396// tnp->tn_did_filefind_init == true: find next file in this part. 2397while (true) { 2398if (tnp -> tn_did_filefind_init ) { 2399fname = vim_findfile (tnp -> tn_search_ctx ); 2400if (fname != NULL ) { 2401break ; 2402 } 2403 2404tnp -> tn_did_filefind_init = false; 2405 }else { 2406char * filename = NULL ; 2407 2408// Stop when used all parts of 'tags'. 2409if (* tnp -> tn_np == NUL ) { 2410vim_findfile_cleanup (tnp -> tn_search_ctx ); 2411tnp -> tn_search_ctx = NULL ; 2412return FAIL ; 2413 } 2414 2415// Copy next file name into buf. 2416buf [0 ]= NUL ; 2417copy_option_part (& tnp -> tn_np ,buf ,MAXPATHL - 1 ," ," ); 2418 2419char * r_ptr = vim_findfile_stopdir (buf ); 2420// move the filename one char forward and truncate the 2421// filepath with a NUL 2422filename = path_tail (buf ); 2423if (r_ptr != NULL ) { 2424STRMOVE (r_ptr + 1 ,r_ptr ); 2425r_ptr ++ ; 2426 } 2427STRMOVE (filename + 1 ,filename ); 2428* filename ++ = NUL ; 2429 2430tnp -> tn_search_ctx = vim_findfile_init (buf ,filename ,strlen (filename ), 2431r_ptr ,100 , 2432 false,// don't free visited list 2433FINDFILE_FILE ,// we search for a file 2434tnp -> tn_search_ctx , true,curbuf -> b_ffname ); 2435if (tnp -> tn_search_ctx != NULL ) { 2436tnp -> tn_did_filefind_init = true; 2437 } 2438 } 2439 } 2440 2441STRCPY (buf ,fname ); 2442xfree (fname ); 2443return OK ; 2444} 2445 2446// Free the contents of a tagname_T that was filled by get_tagfname(). 2447void tagname_free (tagname_T * tnp ) 2448{ 2449xfree (tnp -> tn_tags ); 2450vim_findfile_cleanup (tnp -> tn_search_ctx ); 2451tnp -> tn_search_ctx = NULL ; 2452ga_clear_strings (& tag_fnames ); 2453} 2454 2455/// Parse one line from the tags file. Find start/end of tag name, start/end of 2456/// file name and start of search pattern. 2457/// 2458/// If is_etag is true, tagp->fname and tagp->fname_end are not set. 2459/// 2460/// @param lbuf line to be parsed 2461/// 2462/// @return FAIL if there is a format error in this line, OK otherwise. 2463static int parse_tag_line (char * lbuf ,tagptrs_T * tagp ) 2464{ 2465// Isolate the tagname, from lbuf up to the first white 2466tagp -> tagname = lbuf ; 2467char * p = vim_strchr (lbuf ,TAB ); 2468if (p == NULL ) { 2469return FAIL ; 2470 } 2471tagp -> tagname_end = p ; 2472 2473// Isolate file name, from first to second white space 2474if (* p != NUL ) { 2475p ++ ; 2476 } 2477tagp -> fname = p ; 2478p = vim_strchr (p ,TAB ); 2479if (p == NULL ) { 2480return FAIL ; 2481 } 2482tagp -> fname_end = p ; 2483 2484// find start of search command, after second white space 2485if (* p != NUL ) { 2486p ++ ; 2487 } 2488if (* p == NUL ) { 2489return FAIL ; 2490 } 2491tagp -> command = p ; 2492 2493return OK ; 2494} 2495 2496// Check if tagname is a static tag 2497// 2498// Static tags produced by the older ctags program have the format: 2499// 'file:tag file /pattern'. 2500// This is only recognized when both occurrence of 'file' are the same, to 2501// avoid recognizing "string::string" or ":exit". 2502// 2503// Static tags produced by the new ctags program have the format: 2504// 'tag file /pattern/;"<Tab>file:' " 2505// 2506// Return true if it is a static tag and adjust *tagname to the real tag. 2507// Return false if it is not a static tag. 2508static bool test_for_static (tagptrs_T * tagp ) 2509{ 2510// Check for new style static tag ":...<Tab>file:[<Tab>...]" 2511char * p = tagp -> command ; 2512while ((p = vim_strchr (p ,'\t' ))!= NULL ) { 2513p ++ ; 2514if (strncmp (p ,"file:" ,5 )== 0 ) { 2515return true; 2516 } 2517 } 2518 2519return false; 2520} 2521 2522/// @return the length of a matching tag line. 2523static size_t matching_line_len (const char * const lbuf ) 2524{ 2525const char * p = lbuf + 1 ; 2526 2527// does the same thing as parse_match() 2528p += strlen (p )+ 1 ; 2529return (size_t )(p - lbuf )+ strlen (p ); 2530} 2531 2532/// Parse a line from a matching tag. Does not change the line itself. 2533/// 2534/// The line that we get looks like this: 2535/// Emacs tag: <mtt><tag_fname><NUL><ebuf><NUL><lbuf> 2536/// other tag: <mtt><tag_fname><NUL><NUL><lbuf> 2537/// without Emacs tags: <mtt><tag_fname><NUL><lbuf> 2538/// 2539/// @param lbuf input: matching line 2540/// @param tagp output: pointers into the line 2541/// 2542/// @return OK or FAIL. 2543static int parse_match (char * lbuf ,tagptrs_T * tagp ) 2544{ 2545tagp -> tag_fname = lbuf + 1 ; 2546lbuf += strlen (tagp -> tag_fname )+ 2 ; 2547 2548// Find search pattern and the file name for non-etags. 2549int retval = parse_tag_line (lbuf ,tagp ); 2550 2551tagp -> tagkind = NULL ; 2552tagp -> user_data = NULL ; 2553tagp -> tagline = 0 ; 2554tagp -> command_end = NULL ; 2555 2556if (retval != OK ) { 2557return retval ; 2558 } 2559 2560// Try to find a kind field: "kind:<kind>" or just "<kind>" 2561char * p = tagp -> command ; 2562if (find_extra (& p )== OK ) { 2563tagp -> command_end = p ; 2564if (p > tagp -> command && p [-1 ]== '|' ) { 2565tagp -> command_end = p - 1 ;// drop trailing bar 2566 } 2567p += 2 ;// skip ";\"" 2568if (* p ++ == TAB ) { 2569// Accept ASCII alphabetic kind characters and any multi-byte 2570// character. 2571while (ASCII_ISALPHA (* p )|| utfc_ptr2len (p )> 1 ) { 2572if (strncmp (p ,"kind:" ,5 )== 0 ) { 2573tagp -> tagkind = p + 5 ; 2574 }else if (strncmp (p ,"user_data:" ,10 )== 0 ) { 2575tagp -> user_data = p + 10 ; 2576 }else if (strncmp (p ,"line:" ,5 )== 0 ) { 2577tagp -> tagline = atoi (p + 5 ); 2578 } 2579if (tagp -> tagkind != NULL && tagp -> user_data != NULL ) { 2580break ; 2581 } 2582 2583char * pc = vim_strchr (p ,':' ); 2584char * pt = vim_strchr (p ,'\t' ); 2585if (pc == NULL || (pt != NULL && pc > pt )) { 2586tagp -> tagkind = p ; 2587 } 2588if (pt == NULL ) { 2589break ; 2590 } 2591p = pt ; 2592MB_PTR_ADV (p ); 2593 } 2594 } 2595 } 2596if (tagp -> tagkind != NULL ) { 2597for (p = tagp -> tagkind ; 2598* p && * p != '\t' && * p != '\r' && * p != '\n' ; 2599MB_PTR_ADV (p )) {} 2600tagp -> tagkind_end = p ; 2601 } 2602if (tagp -> user_data != NULL ) { 2603for (p = tagp -> user_data ; 2604* p && * p != '\t' && * p != '\r' && * p != '\n' ; 2605MB_PTR_ADV (p )) {} 2606tagp -> user_data_end = p ; 2607 } 2608return retval ; 2609} 2610 2611// Find out the actual file name of a tag. Concatenate the tags file name 2612// with the matching tag file name. 2613// Returns an allocated string. 2614static char * tag_full_fname (tagptrs_T * tagp ) 2615{ 2616char c = * tagp -> fname_end ; 2617* tagp -> fname_end = NUL ; 2618char * fullname = expand_tag_fname (tagp -> fname ,tagp -> tag_fname , false); 2619* tagp -> fname_end = c ; 2620 2621return fullname ; 2622} 2623 2624/// Jump to a tag that has been found in one of the tag files 2625/// 2626/// @param lbuf_arg line from the tags file for this tag 2627/// @param forceit :ta with ! 2628/// @param keep_help keep help flag 2629/// 2630/// @return OK for success, NOTAGFILE when file not found, FAIL otherwise. 2631static int jumpto_tag (const char * lbuf_arg ,int forceit ,bool keep_help ) 2632{ 2633if (postponed_split == 0 && !check_can_set_curbuf_forceit (forceit )) { 2634return FAIL ; 2635 } 2636 2637char * pbuf_end ; 2638char * tofree_fname = NULL ; 2639tagptrs_T tagp ; 2640int retval = FAIL ; 2641int getfile_result = GETFILE_UNUSED ; 2642int search_options ; 2643win_T * curwin_save = NULL ; 2644char * full_fname = NULL ; 2645const bool old_KeyTyped = KeyTyped ;// getting the file may reset it 2646const int l_g_do_tagpreview = g_do_tagpreview ; 2647const size_t len = matching_line_len (lbuf_arg )+ 1 ; 2648char * lbuf = xmalloc (len ); 2649memmove (lbuf ,lbuf_arg ,len ); 2650 2651char * pbuf = xmalloc (LSIZE );// search pattern buffer 2652 2653// parse the match line into the tagp structure 2654if (parse_match (lbuf ,& tagp )== FAIL ) { 2655tagp .fname_end = NULL ; 2656 gotoerret ; 2657 } 2658 2659// truncate the file name, so it can be used as a string 2660* tagp .fname_end = NUL ; 2661char * fname = tagp .fname ; 2662 2663// copy the command to pbuf[], remove trailing CR/NL 2664char * str = tagp .command ; 2665for (pbuf_end = pbuf ;* str && * str != '\n' && * str != '\r' ;) { 2666* pbuf_end ++ = * str ++ ; 2667if (pbuf_end - pbuf + 1 >=LSIZE ) { 2668break ; 2669 } 2670 } 2671* pbuf_end = NUL ; 2672 2673 { 2674// Remove the "<Tab>fieldname:value" stuff; we don't need it here. 2675str = pbuf ; 2676if (find_extra (& str )== OK ) { 2677// Drop a trailing "|" that terminates a generic Ex command, so it 2678// is not executed as an empty command separator. 2679if (str > pbuf && str [-1 ]== '|' ) { 2680pbuf_end = str - 1 ; 2681 }else { 2682pbuf_end = str ; 2683 } 2684* pbuf_end = NUL ; 2685 } 2686 } 2687 2688// Expand file name, when needed (for environment variables). 2689// If 'tagrelative' option set, may change file name. 2690fname = expand_tag_fname (fname ,tagp .tag_fname , true); 2691tofree_fname = fname ;// free() it later 2692 2693// Check if the file with the tag exists before abandoning the current 2694// file. Also accept a file name for which there is a matching BufReadCmd 2695// autocommand event (e.g., http://sys/file). 2696if (!os_path_exists (fname ) 2697&& !has_autocmd (EVENT_BUFREADCMD ,fname ,NULL )) { 2698retval = NOTAGFILE ; 2699xfree (nofile_fname ); 2700nofile_fname = xstrdup (fname ); 2701 gotoerret ; 2702 } 2703 2704RedrawingDisabled ++ ; 2705 2706if (l_g_do_tagpreview != 0 ) { 2707postponed_split = 0 ;// don't split again below 2708curwin_save = curwin ;// Save current window 2709 2710// If we are reusing a window, we may change dir when 2711// entering it (autocommands) so turn the tag filename 2712// into a fullpath 2713if (!curwin -> w_p_pvw ) { 2714full_fname = FullName_save (fname , false); 2715fname = full_fname ; 2716 2717// Make the preview window the current window. 2718// Open a preview window when needed. 2719prepare_tagpreview (true,* p_pvp != NUL ); 2720 } 2721 } 2722 2723// If it was a CTRL-W CTRL-] command split window now. For ":tab tag" 2724// open a new tab page. 2725if (postponed_split && (swb_flags & (kOptSwbFlagUseopen |kOptSwbFlagUsetab ))) { 2726buf_T * const existing_buf = buflist_findname_exp (fname ); 2727 2728if (existing_buf != NULL ) { 2729// If 'switchbuf' is set jump to the window containing "buf". 2730if (swbuf_goto_win_with_buf (existing_buf )!= NULL ) { 2731// We've switched to the buffer, the usual loading of the file 2732// must be skipped. 2733getfile_result = GETFILE_SAME_FILE ; 2734 } 2735 } 2736 } 2737if (getfile_result == GETFILE_UNUSED 2738&& (postponed_split || cmdmod .cmod_tab != 0 )) { 2739if (swb_flags & kOptSwbFlagVsplit ) { 2740// If 'switchbuf' contains 'vsplit', then use a new vertically 2741// split window. 2742cmdmod .cmod_split |=WSP_VERT ; 2743 } 2744 2745if ((swb_flags & kOptSwbFlagNewtab )&& cmdmod .cmod_tab == 0 ) { 2746// If 'switchbuf' contains 'newtab', then use a new tabpage 2747cmdmod .cmod_tab = tabpage_index (curtab )+ 1 ; 2748 } 2749 2750if (win_split (postponed_split > 0 ?postponed_split :0 , 2751postponed_split_flags )== FAIL ) { 2752RedrawingDisabled -- ; 2753 gotoerret ; 2754 } 2755RESET_BINDING (curwin ); 2756 } 2757 2758if (keep_help ) { 2759// A :ta from a help file will keep the b_help flag set. For ":ptag" 2760// we need to use the flag from the window where we came from. 2761if (l_g_do_tagpreview != 0 ) { 2762keep_help_flag = bt_help (curwin_save -> w_buffer ); 2763 }else { 2764keep_help_flag = curbuf -> b_help ; 2765 } 2766 } 2767 2768if (getfile_result == GETFILE_UNUSED ) { 2769// Careful: getfile() may trigger autocommands and call jumpto_tag() 2770// recursively. 2771getfile_result = getfile (0 ,fname ,NULL , true,0 ,forceit ); 2772 } 2773keep_help_flag = false; 2774 2775if (GETFILE_SUCCESS (getfile_result )) {// got to the right file 2776curwin -> w_set_curswant = true; 2777postponed_split = 0 ; 2778 2779// Save no_hlsearch: jumping to a tag is not a real search 2780const bool save_no_hlsearch = Search .no_hlsearch ; 2781 2782// If 'cpoptions' contains 't', store the search pattern for the "n" 2783// command. If 'cpoptions' does not contain 't', the search pattern 2784// is not stored. 2785if (vim_strchr (p_cpo ,kCpoTagpat )!= NULL ) { 2786search_options = 0 ; 2787 }else { 2788search_options = SEARCH_KEEP ; 2789 } 2790 2791// If the command is a search, try here. 2792// 2793// Reset 'smartcase' for the search, since the search pattern was not 2794// typed by the user. 2795// Only use do_search() when there is a full search command, without 2796// anything following. 2797str = pbuf ; 2798if (pbuf [0 ]== '/' || pbuf [0 ]== '?' ) { 2799str = skip_regexp (pbuf + 1 ,pbuf [0 ], false)+ 1 ; 2800 } 2801if (str > pbuf_end - 1 ) {// search command with nothing following 2802size_t pbuflen = (size_t )(pbuf_end - pbuf ); 2803 2804bool save_p_ws = p_ws ; 2805int save_p_ic = p_ic ; 2806int save_p_scs = p_scs ; 2807p_ws = true;// need 'wrapscan' for backward searches 2808p_ic = false;// don't ignore case now 2809p_scs = false; 2810linenr_T save_lnum = curwin -> w_cursor .lnum ; 2811 2812curwin -> w_cursor .lnum = tagp .tagline > 0 2813// start search before line from "line:" field 2814 ?tagp .tagline - 1 2815// start search before first line 2816 :0 ; 2817 2818if (do_search (NULL ,pbuf [0 ],pbuf [0 ],pbuf + 1 ,pbuflen - 1 ,1 , 2819search_options , false,NULL )) { 2820retval = OK ; 2821 }else { 2822int found = 1 ; 2823 2824// try again, ignore case now 2825p_ic = true; 2826if (!do_search (NULL ,pbuf [0 ],pbuf [0 ],pbuf + 1 ,pbuflen - 1 ,1 , 2827search_options , false,NULL )) { 2828// Failed to find pattern, take a guess: "^func (" 2829found = 2 ; 2830test_for_static (& tagp ); 2831char cc = * tagp .tagname_end ; 2832* tagp .tagname_end = NUL ; 2833pbuflen = (size_t )snprintf (pbuf ,LSIZE ,"^%s\\s\\*(" ,tagp .tagname ); 2834if (!do_search (NULL ,'/' ,'/' ,pbuf ,pbuflen ,1 ,search_options , false,NULL )) { 2835// Guess again: "^char * \<func (" 2836pbuflen = (size_t )snprintf (pbuf ,LSIZE ,"^\\[#a-zA-Z_]\\.\\*\\<%s\\s\\*(" , 2837tagp .tagname ); 2838if (!do_search (NULL ,'/' ,'/' ,pbuf ,pbuflen ,1 ,search_options , false,NULL )) { 2839found = 0 ; 2840 } 2841 } 2842* tagp .tagname_end = cc ; 2843 } 2844if (found == 0 ) { 2845emsg (_ ("E434: Can't find tag pattern" )); 2846curwin -> w_cursor .lnum = save_lnum ; 2847 }else { 2848// Only give a message when really guessed, not when 'ic' 2849// is set and match found while ignoring case. 2850if (found == 2 || !save_p_ic ) { 2851msg (_ ("E435: Couldn't find tag, just guessing!" ),0 ); 2852if (!msg_scrolled && msg_silent == 0 ) { 2853msg_delay (1010 , true); 2854 } 2855 } 2856retval = OK ; 2857 } 2858 } 2859p_ws = save_p_ws ; 2860p_ic = save_p_ic ; 2861p_scs = save_p_scs ; 2862 2863// A search command may have positioned the cursor beyond the end 2864// of the line. May need to correct that here. 2865check_cursor (curwin ); 2866 }else { 2867const int save_secure = secure ; 2868 2869// Setup the sandbox for executing the command from the tags file. 2870secure = 1 ; 2871sandbox ++ ; 2872curwin -> w_cursor .lnum = 1 ;// start command in line 1 2873curwin -> w_cursor .col = 0 ; 2874curwin -> w_cursor .coladd = 0 ; 2875do_cmdline_cmd (pbuf ); 2876retval = OK ; 2877 2878// When the command has done something that is not allowed make sure 2879// the error message can be seen. 2880if (secure == 2 ) { 2881wait_return (true); 2882 } 2883secure = save_secure ; 2884sandbox -- ; 2885 } 2886 2887// restore no_hlsearch when keeping the old search pattern 2888if (search_options ) { 2889set_no_hlsearch (save_no_hlsearch ); 2890 } 2891 2892// Return OK if jumped to another file (at least we found the file!). 2893if (getfile_result == GETFILE_OPEN_OTHER ) { 2894retval = OK ; 2895 } 2896 2897if (retval == OK ) { 2898// For a help buffer: Put the cursor line at the top of the window, 2899// the help subject will be below it. 2900if (curbuf -> b_help ) { 2901set_topline (curwin ,curwin -> w_cursor .lnum ); 2902 } 2903if ((fdo_flags & kOptFdoFlagTag )&& old_KeyTyped ) { 2904foldOpenCursor (); 2905 } 2906 } 2907 2908if (l_g_do_tagpreview != 0 2909&& curwin != curwin_save && win_valid (curwin_save )) { 2910// Return cursor to where we were 2911validate_cursor (curwin ); 2912redraw_later (curwin ,UPD_VALID ); 2913win_enter (curwin_save , true); 2914 } 2915 2916RedrawingDisabled -- ; 2917 }else { 2918RedrawingDisabled -- ; 2919if (postponed_split ) {// close the window 2920win_close (curwin , false, false); 2921postponed_split = 0 ; 2922 } 2923 } 2924 2925erret : 2926g_do_tagpreview = 0 ;// For next time 2927xfree (lbuf ); 2928xfree (pbuf ); 2929xfree (tofree_fname ); 2930xfree (full_fname ); 2931 2932return retval ; 2933} 2934 2935/// If "expand" is true, expand wildcards in fname. 2936/// If 'tagrelative' option set, change fname (name of file containing tag) 2937/// according to tag_fname (name of tag file containing fname). 2938/// 2939/// @return a pointer to allocated memory. 2940static char * expand_tag_fname (char * fname ,char * const tag_fname ,const bool expand ) 2941FUNC_ATTR_NONNULL_RET 2942{ 2943char * p ; 2944char * expanded_fname = NULL ; 2945expand_T xpc ; 2946 2947fname = TO_SLASH_SAVE (fname ); 2948 2949// Expand file name (for environment variables) when needed. 2950// Disallow backticks, they could execute arbitrary shell 2951// commands. This is not needed for tag filenames. 2952if (expand && path_has_wildcard (fname , true)&& vim_strchr (fname ,'`' )== NULL ) { 2953ExpandInit (& xpc ); 2954xpc .xp_context = EXPAND_FILES ; 2955expanded_fname = ExpandOne (& xpc ,fname ,NULL , 2956WILD_LIST_NOTFOUND |WILD_SILENT ,WILD_EXPAND_FREE ); 2957if (expanded_fname != NULL ) { 2958xfree (fname ); 2959fname = expanded_fname ; 2960 } 2961 } 2962 2963char * retval ; 2964if ((p_tr || curbuf -> b_help ) 2965&& !vim_isAbsName (fname ) 2966&& (p = path_tail (tag_fname ))!= tag_fname ) { 2967retval = xmalloc (MAXPATHL ); 2968STRCPY (retval ,tag_fname ); 2969xstrlcpy (retval + (p - tag_fname ),fname , (size_t )(MAXPATHL - (p - tag_fname ))); 2970// Translate names like "src/a/../b/file.c" into "src/b/file.c". 2971simplify_filename (retval ); 2972 }else { 2973retval = xstrdup (fname ); 2974 } 2975 2976xfree (fname ); 2977 2978return retval ; 2979} 2980 2981/// Check if we have a tag for the buffer with name "buf_ffname". 2982/// This is a bit slow, because of the full path compare in path_equal(). 2983/// 2984/// @return true if tag for file "fname" if tag file "tag_fname" is for current 2985/// file. 2986static int test_for_current (char * fname ,char * fname_end ,char * tag_fname ,char * buf_ffname ) 2987{ 2988int retval = false; 2989 2990if (buf_ffname != NULL ) {// if the buffer has a name 2991char c ; 2992 { 2993c = * fname_end ; 2994* fname_end = NUL ; 2995 } 2996char * fullname = expand_tag_fname (fname ,tag_fname , true); 2997retval = path_equal (fullname ,buf_ffname ,kPathCmpExpand |kPathCmpFull ); 2998xfree (fullname ); 2999* fname_end = c ; 3000 } 3001 3002return retval ; 3003} 3004 3005// Find the end of the tagaddress. 3006// Return OK if ";\"" is following, FAIL otherwise. 3007static int find_extra (char ** pp ) 3008{ 3009char * str = * pp ; 3010char first_char = ** pp ; 3011 3012// Repeat for addresses separated with ';' 3013while (true) { 3014if (ascii_isdigit (* str )) { 3015str = skipdigits (str + 1 ); 3016 }else if (* str == '/' || * str == '?' ) { 3017str = skip_regexp (str + 1 ,* str , false); 3018if (* str != first_char ) { 3019str = NULL ; 3020 }else { 3021str ++ ; 3022 } 3023 }else { 3024// not a line number or search string, look for terminator. 3025str = strstr (str ,"|;\"" ); 3026if (str != NULL ) { 3027str ++ ; 3028break ; 3029 } 3030 } 3031if (str == NULL || * str != ';' 3032|| !(ascii_isdigit (str [1 ])|| str [1 ]== '/' || str [1 ]== '?' )) { 3033break ; 3034 } 3035str ++ ;// skip ';' 3036first_char = * str ; 3037 } 3038 3039if (str != NULL && strncmp (str ,";\"" ,2 )== 0 ) { 3040* pp = str ; 3041return OK ; 3042 } 3043return FAIL ; 3044} 3045 3046/// Free a single entry in a tag stack 3047void tagstack_clear_entry (taggy_T * item ) 3048{ 3049XFREE_CLEAR (item -> tagname ); 3050XFREE_CLEAR (item -> user_data ); 3051} 3052 3053/// @param tagnames expand tag names 3054int expand_tags (bool tagnames ,char * pat ,int * num_file ,char *** file ) 3055{ 3056size_t name_buf_size = 100 ; 3057int ret ; 3058 3059char * name_buf = xmalloc (name_buf_size ); 3060 3061int extra_flag = tagnames ?TAG_NAMES :0 ; 3062if (pat [0 ]== '/' ) { 3063ret = find_tags (pat + 1 ,num_file ,file , 3064TAG_REGEXP |extra_flag |TAG_VERBOSE , 3065TAG_MANY ,curbuf -> b_ffname ); 3066 }else { 3067ret = find_tags (pat ,num_file ,file , 3068TAG_REGEXP |extra_flag |TAG_VERBOSE |TAG_NOIC , 3069TAG_MANY ,curbuf -> b_ffname ); 3070 } 3071if (ret == OK && !tagnames ) { 3072// Reorganize the tags for display and matching as strings of: 3073// "<tagname>\0<kind>\0<filename>\0" 3074for (int i = 0 ;i < * num_file ;i ++ ) { 3075tagptrs_T t_p ; 3076parse_match ((* file )[i ],& t_p ); 3077size_t len = (size_t )(t_p .tagname_end - t_p .tagname ); 3078if (len > name_buf_size - 3 ) { 3079name_buf_size = len + 3 ; 3080char * buf = xrealloc (name_buf ,name_buf_size ); 3081name_buf = buf ; 3082 } 3083 3084memmove (name_buf ,t_p .tagname ,len ); 3085name_buf [len ++ ]= 0 ; 3086name_buf [len ++ ]= (t_p .tagkind != NULL && * t_p .tagkind ) 3087 ?* t_p .tagkind :'f' ; 3088name_buf [len ++ ]= 0 ; 3089memmove ((* file )[i ]+ len ,t_p .fname , (size_t )(t_p .fname_end - t_p .fname )); 3090 (* file )[i ][len + (size_t )(t_p .fname_end - t_p .fname )]= 0 ; 3091memmove ((* file )[i ],name_buf ,len ); 3092 } 3093 } 3094xfree (name_buf ); 3095return ret ; 3096} 3097 3098/// Add a tag field to the dictionary "dict". 3099/// Return OK or FAIL. 3100/// 3101/// @param start start of the value 3102/// @param end after the value; can be NULL 3103static int add_tag_field (dict_T * dict ,const char * field_name ,const char * start ,const char * end ) 3104FUNC_ATTR_NONNULL_ARG (1 ,2 ) 3105{ 3106// Check that the field name doesn't exist yet. 3107if (tv_dict_find (dict ,field_name ,-1 )!= NULL ) { 3108if (p_verbose > 0 ) { 3109verbose_enter (); 3110smsg (0 ,_ ("Duplicate field name: %s" ),field_name ); 3111verbose_leave (); 3112 } 3113return FAIL ; 3114 } 3115int len = 0 ; 3116char * buf = xmalloc (MAXPATHL ); 3117if (start != NULL ) { 3118if (end == NULL ) { 3119end = start + strlen (start ); 3120while (end > start && (end [-1 ]== '\r' || end [-1 ]== '\n' )) { 3121end -- ; 3122 } 3123 } 3124len = MIN ((int )(end - start ),MAXPATHL - 1 ); 3125xmemcpyz (buf ,start , (size_t )len ); 3126 } 3127buf [len ]= NUL ; 3128int retval = tv_dict_add_str (dict ,field_name ,strlen (field_name ),buf ); 3129xfree (buf ); 3130return retval ; 3131} 3132 3133/// Add the tags matching the specified pattern "pat" to the list "list" 3134/// as a dictionary. Use "buf_fname" for priority, unless NULL. 3135int get_tags (list_T * list ,char * pat ,char * buf_fname ) 3136{ 3137int num_matches ; 3138char ** matches ; 3139tagptrs_T tp ; 3140 3141int ret = find_tags (pat ,& num_matches ,& matches ,TAG_REGEXP |TAG_NOIC ,MAXCOL ,buf_fname ); 3142if (ret != OK || num_matches <=0 ) { 3143return ret ; 3144 } 3145 3146for (int i = 0 ;i < num_matches ;i ++ ) { 3147if (parse_match (matches [i ],& tp )== FAIL ) { 3148xfree (matches [i ]); 3149continue ; 3150 } 3151 3152bool is_static = test_for_static (& tp ); 3153 3154// Skip pseudo-tag lines. 3155if (strncmp (tp .tagname ,"!_TAG_" ,6 )== 0 ) { 3156xfree (matches [i ]); 3157continue ; 3158 } 3159 3160dict_T * dict = tv_dict_alloc (); 3161tv_list_append_dict (list ,dict ); 3162 3163char * full_fname = tag_full_fname (& tp ); 3164if (add_tag_field (dict ,"name" ,tp .tagname ,tp .tagname_end )== FAIL 3165|| add_tag_field (dict ,"filename" ,full_fname ,NULL )== FAIL 3166|| add_tag_field (dict ,"cmd" ,tp .command ,tp .command_end )== FAIL 3167|| add_tag_field (dict ,"kind" ,tp .tagkind , 3168tp .tagkind ?tp .tagkind_end :NULL )== FAIL 3169|| tv_dict_add_nr (dict ,S_LEN ("static" ),is_static )== FAIL ) { 3170ret = FAIL ; 3171 } 3172 3173xfree (full_fname ); 3174 3175if (tp .command_end != NULL ) { 3176for (char * p = tp .command_end + 3 ; 3177* p != NUL && * p != '\n' && * p != '\r' ; 3178MB_PTR_ADV (p )) { 3179if (p == tp .tagkind 3180|| (p + 5 == tp .tagkind && strncmp (p ,"kind:" ,5 )== 0 )) { 3181// skip "kind:<kind>" and "<kind>" 3182p = tp .tagkind_end - 1 ; 3183 }else if (strncmp (p ,"file:" ,5 )== 0 ) { 3184// skip "file:" (static tag) 3185p += 4 ; 3186 }else if (!ascii_iswhite (* p )) { 3187int len ; 3188 3189// Add extra field as a dict entry. Fields are 3190// separated by Tabs. 3191char * n = p ; 3192while (* p != NUL && * p >=' ' && * p < 127 && * p != ':' ) { 3193p ++ ; 3194 } 3195len = (int )(p - n ); 3196if (* p == ':' && len > 0 ) { 3197char * s = ++ p ; 3198while (* p != NUL && (uint8_t )(* p ) >=' ' ) { 3199p ++ ; 3200 } 3201n [len ]= NUL ; 3202if (add_tag_field (dict ,n ,s ,p )== FAIL ) { 3203ret = FAIL ; 3204 } 3205n [len ]= ':' ; 3206 }else { 3207// Skip field without colon. 3208while (* p != NUL && (uint8_t )(* p ) >=' ' ) { 3209p ++ ; 3210 } 3211 } 3212if (* p == NUL ) { 3213break ; 3214 } 3215 } 3216 } 3217 } 3218 3219xfree (matches [i ]); 3220 } 3221xfree (matches ); 3222return ret ; 3223} 3224 3225// Return information about 'tag' in dict 'retdict'. 3226static void get_tag_details (taggy_T * tag ,dict_T * retdict ) 3227{ 3228tv_dict_add_str (retdict ,S_LEN ("tagname" ),tag -> tagname ); 3229tv_dict_add_nr (retdict ,S_LEN ("matchnr" ),tag -> cur_match + 1 ); 3230tv_dict_add_nr (retdict ,S_LEN ("bufnr" ),tag -> cur_fnum ); 3231if (tag -> user_data ) { 3232tv_dict_add_str (retdict ,S_LEN ("user_data" ),tag -> user_data ); 3233 } 3234 3235list_T * pos = tv_list_alloc (4 ); 3236tv_dict_add_list (retdict ,S_LEN ("from" ),pos ); 3237 3238fmark_T * fmark = & tag -> fmark ; 3239tv_list_append_number (pos , 3240 (varnumber_T )(fmark -> fnum != -1 ?fmark -> fnum :0 )); 3241tv_list_append_number (pos , (varnumber_T )fmark -> mark .lnum ); 3242tv_list_append_number (pos , (varnumber_T )(fmark -> mark .col == MAXCOL 3243 ?MAXCOL :fmark -> mark .col + 1 )); 3244tv_list_append_number (pos , (varnumber_T )fmark -> mark .coladd ); 3245} 3246 3247// Return the tag stack entries of the specified window 'wp' in dictionary 3248// 'retdict'. 3249void get_tagstack (win_T * wp ,dict_T * retdict ) 3250{ 3251tv_dict_add_nr (retdict ,S_LEN ("length" ),wp -> w_tagstacklen ); 3252tv_dict_add_nr (retdict ,S_LEN ("curidx" ),wp -> w_tagstackidx + 1 ); 3253list_T * l = tv_list_alloc (2 ); 3254tv_dict_add_list (retdict ,S_LEN ("items" ),l ); 3255 3256for (int i = 0 ;i < wp -> w_tagstacklen ;i ++ ) { 3257dict_T * d = tv_dict_alloc (); 3258tv_list_append_dict (l ,d ); 3259get_tag_details (& wp -> w_tagstack [i ],d ); 3260 } 3261} 3262 3263// Free all the entries in the tag stack of the specified window 3264static void tagstack_clear (win_T * wp ) 3265{ 3266// Free the current tag stack 3267for (int i = 0 ;i < wp -> w_tagstacklen ;i ++ ) { 3268tagstack_clear_entry (& wp -> w_tagstack [i ]); 3269 } 3270wp -> w_tagstacklen = 0 ; 3271wp -> w_tagstackidx = 0 ; 3272} 3273 3274// Remove the oldest entry from the tag stack and shift the rest of 3275// the entries to free up the top of the stack. 3276static void tagstack_shift (win_T * wp ) 3277{ 3278taggy_T * tagstack = wp -> w_tagstack ; 3279tagstack_clear_entry (& tagstack [0 ]); 3280for (int i = 1 ;i < wp -> w_tagstacklen ;i ++ ) { 3281tagstack [i - 1 ]= tagstack [i ]; 3282 } 3283wp -> w_tagstacklen -- ; 3284} 3285 3286/// Push a new item to the tag stack 3287static void tagstack_push_item (win_T * wp ,char * tagname ,int cur_fnum ,int cur_match ,pos_T mark , 3288int fnum ,char * user_data ) 3289{ 3290taggy_T * tagstack = wp -> w_tagstack ; 3291int idx = wp -> w_tagstacklen ;// top of the stack 3292 3293// if the tagstack is full: remove the oldest entry 3294if (idx >=TAGSTACKSIZE ) { 3295tagstack_shift (wp ); 3296idx = TAGSTACKSIZE - 1 ; 3297 } 3298 3299wp -> w_tagstacklen ++ ; 3300tagstack [idx ].tagname = tagname ; 3301tagstack [idx ].cur_fnum = cur_fnum ; 3302tagstack [idx ].cur_match = cur_match ; 3303tagstack [idx ].cur_match = MAX (tagstack [idx ].cur_match ,0 ); 3304tagstack [idx ].fmark .mark = mark ; 3305tagstack [idx ].fmark .fnum = fnum ; 3306tagstack [idx ].fmark .view = (fmarkv_T )INIT_FMARKV ; 3307tagstack [idx ].user_data = user_data ; 3308} 3309 3310/// Add a list of items to the tag stack in the specified window 3311static void tagstack_push_items (win_T * wp ,list_T * l ) 3312{ 3313dictitem_T * di ; 3314char * tagname ; 3315pos_T mark ; 3316int fnum ; 3317 3318// Add one entry at a time to the tag stack 3319for (listitem_T * li = tv_list_first (l );li != NULL ;li = TV_LIST_ITEM_NEXT (l ,li )) { 3320if (TV_LIST_ITEM_TV (li )-> v_type != VAR_DICT 3321|| TV_LIST_ITEM_TV (li )-> vval .v_dict == NULL ) { 3322continue ;// Skip non-dict items 3323 } 3324dict_T * itemdict = TV_LIST_ITEM_TV (li )-> vval .v_dict ; 3325 3326// parse 'from' for the cursor position before the tag jump 3327if ((di = tv_dict_find (itemdict ,"from" ,-1 ))== NULL ) { 3328continue ; 3329 } 3330if (list2fpos (& di -> di_tv ,& mark ,& fnum ,NULL , false)!= OK ) { 3331continue ; 3332 } 3333if ((tagname = tv_dict_get_string (itemdict ,"tagname" , true))== NULL ) { 3334continue ; 3335 } 3336 3337if (mark .col > 0 ) { 3338mark .col -- ; 3339 } 3340tagstack_push_item (wp , 3341tagname , 3342 (int )tv_dict_get_number (itemdict ,"bufnr" ), 3343 (int )tv_dict_get_number (itemdict ,"matchnr" )- 1 , 3344mark ,fnum , 3345tv_dict_get_string (itemdict ,"user_data" , true)); 3346 } 3347} 3348 3349// Set the current index in the tag stack. Valid values are between 0 3350// and the stack length (inclusive). 3351static void tagstack_set_curidx (win_T * wp ,int curidx ) 3352{ 3353wp -> w_tagstackidx = curidx ; 3354// sanity check 3355wp -> w_tagstackidx = MIN (MAX (wp -> w_tagstackidx ,0 ),wp -> w_tagstacklen ); 3356} 3357 3358// Set the tag stack entries of the specified window. 3359// 'action' is set to one of: 3360// 'a' for append 3361// 'r' for replace 3362// 't' for truncate 3363int set_tagstack (win_T * wp ,const dict_T * d ,int action ) 3364FUNC_ATTR_NONNULL_ARG (1 ) 3365{ 3366// not allowed to alter the tag stack entries from inside tagfunc 3367if (tfu_in_use ) { 3368emsg (_ (e_cannot_modify_tag_stack_within_tagfunc )); 3369return FAIL ; 3370 } 3371 3372dictitem_T * di ; 3373list_T * l = NULL ; 3374 3375if ((di = tv_dict_find (d ,"items" ,-1 ))!= NULL ) { 3376if (di -> di_tv .v_type != VAR_LIST ) { 3377emsg (_ (e_listreq )); 3378return FAIL ; 3379 } 3380l = di -> di_tv .vval .v_list ; 3381 } 3382 3383if ((di = tv_dict_find (d ,"curidx" ,-1 ))!= NULL ) { 3384tagstack_set_curidx (wp , (int )tv_get_number (& di -> di_tv )- 1 ); 3385 } 3386 3387if (action == 't' ) {// truncate the stack 3388taggy_T * const tagstack = wp -> w_tagstack ; 3389const int tagstackidx = wp -> w_tagstackidx ; 3390int tagstacklen = wp -> w_tagstacklen ; 3391 3392// delete all the tag stack entries above the current entry 3393while (tagstackidx < tagstacklen ) { 3394tagstack_clear_entry (& tagstack [-- tagstacklen ]); 3395 } 3396wp -> w_tagstacklen = tagstacklen ; 3397 } 3398 3399if (l != NULL ) { 3400if (action == 'r' ) {// replace the stack 3401tagstack_clear (wp ); 3402 } 3403 3404tagstack_push_items (wp ,l ); 3405// set the current index after the last entry 3406wp -> w_tagstackidx = wp -> w_tagstacklen ; 3407 } 3408 3409return OK ; 3410}