Looking for a way to correctly order ctags matches - vim

I have a codebase that has ctags configured correctly. When I do, :tjump keyword it shows me a list of potential matches for the keyword.
However these matches aren't ordered correctly. I'm looking for a way to correctly order the matches so that the best match is at the top of the list. ie:- the first jump when I directly use Ctrl-] should go to the correct place.
For the GetFile navigation with gf I have found includeexpr which allows me to run custom logic to determine the file to jump to.
Does Vim have a similar function for altering the tags results?
Another approach I am considering is to grab the list of tags from :tjump, do sorting, and override the mapping for Ctrl-].
For this approach, is there a function to get the list of matches from :tjump?
Any other ideas to ensure that the the correct match is at the top are also welcome!
Thanks.

It's often not clear what the "correct" match is. Currently Vim uses the following logic (from :help tag-priority):
When there are multiple matches for a tag, this priority is used:
1. "FSC" A full matching static tag for the current file.
2. "F C" A full matching global tag for the current file.
3. "F " A full matching global tag for another file.
4. "FS " A full matching static tag for another file.
5. " SC" An ignore-case matching static tag for the current file.
6. " C" An ignore-case matching global tag for the current file.
7. " " An ignore-case matching global tag for another file.
8. " S " An ignore-case matching static tag for another file.
If you want to implement your own custom logic, there's nothing (that I know of) similar to the includeexpr that can help you.
You could create multiple tags and order them in the tags setting in such a way that encodes your preference. It's hard to say what that would be, though, and very likely to require some experimenting.
Another, more complicated thing you could do is override the <c-]> key (and maybe others, like <c-w>]) to do something different. Something like:
nnoremap <c-]> :call <SID>JumpToTag()<cr>
function! s:JumpToTag()
" try to find a word under the cursor
let current_word = expand("<cword>")
" check if there is one
if current_word == ''
echomsg "No word under the cursor"
return
endif
" find all tags for the given word
let tags = taglist('^'.current_word.'$')
" if no tags are found, bail out
if empty(tags)
echomsg "No tags found for: ".current_word
return
endif
" take the first tag, or implement some more complicated logic here
let selected_tag = tags[0]
" edit the relevant file, jump to the tag's position
exe 'edit '.selected_tag.filename
exe selected_tag.cmd
endfunction
You can use the taglist() function to locate the tags for the word under the cursor. Then, instead of let selected_tag = tags[0], you can implement your own logic, like filtering out test files, or sorting by certain criteria.
Unfortunately, this doesn't maintain the :tnext and :tprevious commands, since you're manually editing files. You could replace it with the quickfix or the location list, using the setqflist() function with the tags ordered the way you like and then navigate using :cnext and :cprev. But that's a whole lot of more scripting :). If you decide to go down this rabbit hole, you might want to take a look at the source of my tagfinder plugin for inspiration.

Based on your comment to #AndrewRadev's answer:
I often create a "mktags" script that builds ctags and then filters out of the tags file the ones I want to omit. For example (for sh, ksh, bash, zsh):
ctags "$#"
egrep -v "RE-for-tags-to-delete" tags > tags.$$
mv tags.$$ tags

Related

How to autocomplete in vim based off partial matching via ctags

Example:
In a file in another directory I have a function defined by the following:
def _generator_function_1(self):
passs
In the file of my current directory, I have typed the following:
def test_generI
where I denotes my cursor position.
I would like to use vim's autocompletion functionality (i.e. via ^n or ^p) to autocomplete the function definition to test_generator_function_1. Is there a way of configuring vim autocompletion to match not based off full-prefixes? Or, is there a way in ctags to generate tags based off keywords instead of full function definitions?
EDIT:
To clarify, I am specifically wondering if keyword-based autocompletion exists. I have autocompletion by tags setting up, so if I typed "_gen", then ^n would complete to give me "_generator_function_1". In my example, however, it is because the string is prefixed by "test" that "test_gener" as the starting typed word does not lead to any autocomplete suggestions. So I am wondering if this can somehow be made possible.
Vim doesn't have "autocompletion functionality". It only has "completion", not "autocompletion". You need a plugin for "autocompletion".
No, there's no way to obtain your desired behavior without some serious vimscripting. See :help complete-functions.

Cscope Syntax hightlight search within search

I am using CSCOPE for my project and I have few question.
1) Can I color the search result (mostly when I serach using
":cs f s " i.e. within the open file.
2) Is there a way to search within search? Like I search "ret_val" and it gave 1000 result, instead of going each line, can I search some more like folder name etc?
I am not sure how you use the tool, but generally, the answer is yes.
1) You could either redirect results to file, lets say out.cscope then create syntax file for file type *.csope OR, use a function to run the tool, then locally set up the buffer with adequate hi and match options
2) If you saved search results in a cscope file then you can search it normally. Otherwise you can redir output to new tab/split and again search the buffer (which now doesn't need to have externally associated file. I suggest you to use vim-foldsearch plugin to fold out anything (not) in the match. You can even delete folded sections (with or without any number of context lines) so that only stuff you are interested in finally remains in the buffer (i.e. it behaves like filter). Alternatively you can use unite plugin and it filtering source lines which filters lines as you type the keyword. Actually, I would personally go with that option as it provides most interactive way of working.

Lookup a specific kind of tag in Vim

So here's my problem. I've gotten exuberant ctags working with Vim, and it works great, most of the time. One thing that still irks me though is whenever I try to search for a function that is named the same as some variable name. I sometimes get the right tag on the first try, sometimes not. Then after I pull up the list of alternate tags with :tselect, it comes up with a list of tags for both function definitions or variable definitions/assignments. (I'm in PHP so definitions and assignments are syntactically indistinguishable).
However, I notice that there's a column labeled 'kind' that has a value of 'f' or 'v', for function and variable, respectively. I can't seem to find a whole lot of information about this field, it seems like it may not be exactly standardized or widely used. My question is: can you filter tag results in Vim by "kind"?
Ideally, the default would be to search the whole tags file, but by specifying some extra flag, you could search a specific ('f' or 'v') kind only.
This is such a small problem for me as it doesn't come up THAT often, but sometimes it's the small problems that really annoy you.
You can certainly generate ctag files with any combination of php-kinds that you want (see the ouput of the command ctags --list-kinds.)
If you feel it's worth the effort you can make a vim function tagkind and bind it to a command. The tagkind function can overwrite the current tags vim variable to point at only the tag file with the kinds that you are interested in and call :tag. Optionally, it can store the previous version of the tags variable and restore it after this one call.
Unfortunately, I don't know of anyway other than this. Perhaps someone else would know.
I generate python ctags with --python-kinds=-i to exclude tags for import statements (which are useless). Maybe you could generate with --php-kinds=-v and drop a class of tags completely.
You can read :help tag-priority. Apparently the "highest-priority" tag is chosen based on some hard-coded logic.
fzf with fzf.vim has a :Tags (for the whole project) and :BTags for the current file option that generates ctags on the fly.
An issue raised on the plugin 'Skip tag kinds in :BTags and :Tags' gives the following code that you can use to only generated tags for a particular kind. I've modified the below so that it should only search for the PHP f kind.
command! BTagsEnhanced
\ call fzf#vim#buffer_tags(<q-args>, [
\ printf('ctags -f - --sort=no --php-kinds=f --excmd=number --language-force=%s %s', &filetype, expand('%:S'))], {})
Note as per my comment on the question, there is a potential Vim tagfinder.vim plugin via a blog post on Vim and Ctags: Finding Tag Definitions. But I haven't tried it.

in vim, how to combine ^] and arge, to follow a tag and also add it to the arg list?

I can get the word under the cursor with or , and I can use that to open a file and add it to the arg list. For example, with the cursor over a java class name, at line 45:
:arge +45 mydirhere/<cword>.java
But I don't know how to pass into the the tag mechanism, so it will return the file name (and line number), that can be passed to arge
So I guess my question is specifically: "how do you call the tag mechanism?" I'm expecting something like:
String getFileAndLineforTag(String tag)
You can use the taglist() function. From :help taglist() (in Vim 7.1):
taglist({expr}) *taglist()*
Returns a list of tags matching the regular expression {expr}.
Each list item is a dictionary with at least the following
entries:
name Name of the tag.
filename Name of the file where the tag is
defined. It is either relative to the
current directory or a full path.
cmd Ex command used to locate the tag in
the file.
kind Type of the tag. The value for this
entry depends on the language specific
kind values. Only available when
using a tags file generated by
Exuberant ctags or hdrtag.
static A file specific tag. Refer to
|static-tag| for more information.
More entries may be present, depending on the content of the
tags file: access, implementation, inherits and signature.
Refer to the ctags documentation for information about these
fields. For C code the fields "struct", "class" and "enum"
may appear, they give the name of the entity the tag is
contained in.
The ex-command 'cmd' can be either an ex search pattern, a
line number or a line number followed by a byte number.
If there are no matching tags, then an empty list is returned.
To get an exact tag match, the anchors '^' and '$' should be
used in {expr}. Refer to |tag-regexp| for more information
about the tag search regular expression pattern.
Refer to |'tags'| for information about how the tags file is
located by Vim. Refer to |tags-file-format| for the format of
the tags file generated by the different ctags tools.
When you define a custom command you can specify -complete=tag or
-complete=tag_listfiles. If you need to do something more elaborate you can use -complete=custom,{func} or -complete=customlist,{func}. See :help :command-completion for more on this.
Here's some code to do it though not going to the right line, using Laurence Gonsalves's answer (thanks!)
:exe "arge " . taglist(expand("<cword>"))[0].filename
A confusing part was how to integrate the worlds of functions and ordinary commands, which is done with ("exe") and string concatention (".")

How to quickly change variable names in Vim?

I am using Vim to read through a lot of C and Perl code containing many single letter variable names.
It would be nice to have some command to change the name of a variable to something more meaningful while I’m in the process of reading the code, so that I could read the rest of it faster.
Is there some command in Vim which could let me do this quickly?
I don’t think regexes would work because:
the same single letter name might have different purposes in different scoping blocks; and
the same combination of letters could be part of another longer variable name, a string literal, or a comment.
Are there any known solutions?
The following is how to rename a variable which is defined in the current scope {}.
Move your cursor to the variable usage. Press gd. Which means - move cursor to the definition.
Now Press [{ - this will bring you to the scope begin.
Press V - will turn on Visual Line selection.
Press % - will jump to the opposite } thus will select the whole scope.
Press :s/ - start of the substitute command.
<C-R>/ - will insert pattern that match variable name (that name you were on before pressing gd).
/newname/gc<CR> - will initiate search and replace with confirmation on every match.
Now you have to record a macros or even better - map a key.
Here are the final mappings:
" For local replace
nnoremap gr gd[{V%::s/<C-R>///gc<left><left><left>
" For global replace
nnoremap gR gD:%s/<C-R>///gc<left><left><left>
Put this to your .vimrc or just execute.
After this pressing gr on the local variable will bring you to :s command where you simply should enter new_variable_name and press Enter.
I know it's an old question, and #mykola-golubyev's way obviously IS the best answer for the particular case in the OP question (which, I assume is going through obfuscated code where you're likely to have multiple blocks with same var names); but with the question name like that many people coming here from google searches probably look for less situation-specific ways to rename variables in VIM -- and those can be more concise
I'm surprised no one suggested this way:
* :s// NEWNAME /gc
The * is the same as gn - search the next occurrence of the word under the cursor AND make it the last searched pattern; you can then omit the search pattern in the substitute command and VIM will assume that last one is the pattern to search for.
For small amounts of var copies, here's an even quicker one:
* cw NEWNAME <esc> then repeat n. for other occurrences
* is search for occurrences, cw is change word, n goes to the next occurrence of the last searched term and . repeats the last command (which is now change word to NEWNAME)
(Credits for me knowing all this go to #doomedbunnies on Reddit)
Another cool trick: (credits to #nobe4)
* cgn NEWNAME <esc> then repeat . for other occurrences
cgn is "change whatever is the result of (find next occurrence)". Now that this is the last command, you don't need the n to go to the next occurrence, so fewer strokes again, and, more importantly, no need to alternate n and .. But, obviously, this one has the drawback of not having a way to skip an occurrence.
Here are some benefits of these over other similar approaches, or language-specific plugins with refactoring support:
no command mapping, no fiddling with .vimrc(or init.vim), so you can use it in any VIM copy you come across (e.g. a quick task on some VPS or your friend's machine where configuring VIM your way would defeat the purpose of 'quick')
using * or gn for word selection is very quick -- just one keystroke (well, let's say 1.5)
using * or gn makes sure you don't get any matches inside other words, just as :%s/<C-R>//gc does. Beats typing the :%s/\<OLDNAME\>/NEWNAME/gc by hand: I personally tend to forget to use the \< things to limit matches to whole words only.
Not using a scope will only result in a few extra strokes of n to skip unwanted matches -- probably even fewer than the extra strokes needed to limit the scope to a certain code block. Under normal circumstances, your variables are most likely somewhat localised to a certain code block anyway.
AFAIK, there is no actual refactoring support in VIM. When doing a rename with the intent of a refactor I usually take the following precautions:
Limit the scope of the change my using marks.
When entering the regex, bracket the name with \< and >. This will make it match an entire word which reduces the types of incorrect renames that will occur.
Don't do a multiline replace to reduce chances of a bad replace
Look through the code diff carefully if it's anything other than a small change.
My end change looks something like this
:'a,'bs/\<foo\>/bar
I would love to be wrong about there not being a refactoring tool for VIM but I haven't seen it.
Put this in your .vimrc
" Function to rename the variable under the cursor
function! Rnvar()
let word_to_replace = expand("<cword>")
let replacement = input("new name: ")
execute '%s/\(\W\)' . word_to_replace . '\(\W\)/\1' . replacement . '\2/gc'
endfunction
Call it with :call Rnvar()
expand("<cword>") gets the word under the cursor. The search string uses % for file-scope, and the \(\W\) patterns look for non-word characters at the boundary of the word to replace, and save them in variables \1 and \2 so as to be re-inserted in the replacement pattern.
You could use the 'c' modifier in the global search and replace that would ask you for confirmation for each replace. It would take longer but it might work for a non-humongous code file:
%s/\$var/\$foo/gc
The c stands for confirm.
In c, you may be able to make some progress using cscope. It makes an attempt at understanding syntax, so would have a chance of knowing when the letter was a variable.
If this is across multiple files, you may consider taking a look at sed. Use find to grab your files and xargs plus sed for a replace. Say you want to replace a with a_better_name in all files matching *.c, you could do
find . -name "*.c" | xargs sed -i -e 's/a/a_better_name/g'
Bear in mind that this will replace ALL occurrences of a, so you may want a more robust regex.

Resources