.vimrc TAGS command errors - vim

I use etags with vim on linux for source(*.c, *.h) code browsing. I have created a TAGS file bu giving command :
etags --members *.c *.h
TAGS file gets created but when I start browsing say one of the source files named 1.c which has a C structure variable defined and used in one of its function definitions(The structure name is a typedef in some other 1.h file). I open the file 1.c in vim and then I do CTRL - ] by placing cursor on that struct type, etags does not browse to the header file 1.h which has declaration of this structure.
This only happens when i have below line in my .vimrc, when i comment below two lines, etags based source browsing works fine.
set TAGS=./TAGS;$HOME
set tags=./tags;$HOME
I am trying to tell vim where to locate the TAGS file. starting from current folder till my home dir. What is incorrect here?
What is the correct syntax for above command?
Also does ctags/etags browsing with vim, show from where all a given function is called from?
If yes, what is the command to see that?

Locating tags file
Vim's settings are case-sensitive so set TAGS= is invalid. You must use set tags= in lowercase.
Vim will stop at the first match so you can't really expect it to search for a tag in tags and TAGS. These files can be searched in turn with:
set tags=./tags,./TAGS;$HOME " 1. tags, 2. TAGS, 3.… until $HOME
Also, search is not performed by etags, it's done by Vim itself.
Jumping to function calls
No, ctags and etags only index declarations. To jump to usage you'll need cscope

Related

Edit Help file outside doc directory causes tags not to work when copying in

I've created a help file under $VIM\vimfiles\doc. After nearly deleting it I wanted to edit it elsewhere and then copy it to the doc directory and then regenerate the tags.
The tags are generated , I can see them in the tagfile, but the file that I copy in, unique name, when I do :h sfcontents for eg and then ctrl-] on a tag I get the error "e426 tag not found"
If I edit the file in the $VIM\vimfiles\doc directory and then run either :Helptags or :helptags $VIM\vimfiles\doc the tag jump works
I can't attach a file but the help file looks something like
vim: filetype=help foldmethod=indent foldclose=all modifiable noreadonly
Table of Contents *sfcontents*
*sfsearch* - Search specific commands help
|count-matches-of-pattern|
|match-specific-column|
...
==============================================================================
count-matches-of-pattern
*count-matches-of-pattern*
:%s/pattern//gn
counts the number of the matches in a file eg count the number of spaces
not at the beginning of a line
:%s/[^ ]\+//gn
==============================================================================
*match-specific-column*
c=column l=line v=virtual column, ie ignore tabs and special chars
/\%5cx will match all occurrences of x at column 5.
/\%>5vx will match all occurrences of x after character 5. If there is a
tab character between poition 1 and position 5 the /\%5>v. against the
following line with a tab at position 4 will return the number 4
123 45
/\%>4cx\%<7cx will match all occurrences of x after column 4 and before
column 7
Or use |YankMatchesToReg| eg YankMatchesToReg /\%265v./x which copies
column 265 to register x across the whole file
==============================================================================
...
vim:tw=88:ts=4:ft=help:norl
I've ended up doing the archive out of the vim directory with the following;
nmap <leader>c :sp C:\Progra~2\vim\vimfiles\doc\commands.txt<cr>
nmap <leader>co :call BackupCommands()<cr>
function! BackupCommands()
exec "silent! !copy C:\\Progra~2\\Vim\\vimfiles\\doc\\commands.txt
C:\\Progra~2\\vimutils\\vimtips\\commands_back.txt"
exec "helptags C:\\Progra~2\\Vim\\vimfiles\\doc\\"
endfunction
I'd prefer to copy from the archive to the doc directory rather than the other way round. Any suggestions.
Straight from Vim's help files (:h write-local-help):
The first line is actually the only one for which the format matters. It will
be extracted from the help file to be put in the "LOCAL ADDITIONS:" section of
help.txt |local-additions|. The first "*" must be in the first column of the
first line. After adding your help file do ":help" and check that the entries
line up nicely.
Short: You're missing *sfsearch.txt* as first characters in your file!
Vim wont add to |local-additions|, therefore wont be searched, assuming your tags file was generated correctly. You can verify that by opening the tags file in the /doc directory and finding your tags there manually. There should be a tags file in each correctly helptagged /doc directory (:helptags <doc-dir>).
IMO, fear of "nearly deleting" a file is not a proper reason for editing in another location and copying back and forth. In fact, you've now introduced another risk of accidentally losing file contents via a wrong copy command.
Instead, use proper version control (Git, Mercurial, etc.), or, if that's too heavyweight, you can try my writebackup plugin, a pure Vimscript implementation. With the companion writebackupToAdjacentDir plugin, you can even backup to other directories.
That said, tag jumping should work even with your copy regime, provided that you run :helptags $VIM\vimfiles\doc after copying your help file to that exact location.

vim set working directory

When I switch buffers in Vim (using :bn and :bp), I want it to automatically set the working directory, BUT not to be the directory of the opened file. I want Vim to search recursively upwards for a file called "tags", and when it finds that file, set the working directory to the directory with the "tags" file.
Example:
:e ~/programming/projects/foobar/src/js/scripts.js
As you can see, "foobar" is kind of the "project root". Let's assume the "tags" file is in the foobar directory. Now Vim should look in "js", but there's no tags file. Then it should look in "src", no tags file there. Then it should look in "foobar" and find the "tags" file, then do:
:cd ~/programming/projects/foobar/
Is there a simple way to do this? :)
If your whole point is to get to the correct "tags"-file then this could be done easier:
set tags=./tags,tags;$HOME/programming,$HOME/programming/your/global/tags
The tags option accepts a comma (or space) delimited list of entries. In my example I have the following entries:
./tags this means it should look first for a tags-file in the current directory
tags;$HOME/programming this means look for a tags-file from the current directory up to $HOME/programming (that's what the semicolon does, see file-searching). If you don't specify the "stop"-directory using the semicolon then it searches up to the root directory /
$HOME/programming/your/global/tags lastly this is a tags file referred to by absolute file name
My example is probably overkill for your purpose from your description you only need this:
set tags=tags;$HOME/programming
But if you really need to change the working directory then you could add something like this (change lcd to cd if you have to) to your .vimrc:
au BufNewFile,BufRead *.js execute ":lcd " . fnamemodify(findfile("tags", ".;"), ":p:h")
Disclaimer: I'm the author of the mentioned plugin.
I think you could use the little codepath.vim. I wrote it because I was in need of a little function that would help me to reach my project root. The plugin makes the assumption you have a folder with all your code. Something like $HOME/code. Well, it provides the following function:
codepath#path()
I use in combinations with plugins like NERDTree or command-t. So I can open a NERDTree window in my project root. It really is a little plugin but I use it all the time.

How to search the tags file and load it automatically when vim start up

Vim is my favorite editor, when I open a php or python file in vim, the first command is:
set tags=../../../tags
or
set tags=../../tags
I think vim can do this automatically:
first search ./tags, if it is exists, set it, if not exists
search ../tags,if it is exists, set it, if not exists
search ../../tags,if it is exists, set it, if not exists
until it reaches the / or D: directory
However, I am not so familiar with the vim scripts.
Any of your help will be appreciated!_
There are a few comments on this particular subject on this question.
Basically, this is supposed to work:
set tags=./tags;/
It starts with a tags file in the current directory and goes up to the root directory.
Type :help tags-option for more details.

How to switch between multiple vim configurations with a command or local vimrc files?

I work in several groups, each of which has its own tab/indentation/spacing standards in C.
Is there a way to have separate selectable VIM configurations for each so, when I edit a file, either:
I do something like set group=1 to select a configuration
a local .vimrc that lives in the working directory is used to set the configuration automatically
I have this in $HOME/.vimrc:
if filereadable(".vim.custom")
so .vim.custom
endif
This allows me to put a .vim.custom file in every directory to load commands and options specific to that directory. If you're working on multiple projects that have deep directory structures you might need something more sophisticated (e.g. walk up the directory tree until a .vim.custom is found), but the same basic idea will work.
UPDATE:
I now do something like this in order to read a .vim file from the same directory as the file I'm editing, regardless of what the current directory is.
let b:thisdir=expand("%:p:h")
let b:vim=b:thisdir."/.vim"
if (filereadable(b:vim))
execute "source ".b:vim
endif
In Summary
There are a few ways to do this, of which most have been suggested, but I thought I'd summarise them with two extra ones:
Per-directory vimrc - has the disadvantage that Vim must be started in the right directory: if your project is in ~/project1 and you have ~/project1/.vim.custom and do cd ~ ; vim project1/file.c, the custom settings won't be found.
Modelines - very effective, but has the disadvantage of needing to add them to all files (and remember to add them to new files)
Directory specific autocommands - this is very effective
Scan for a specific header in the file (see below) - this is the one I've used most in the past where working for different companies or on clearly named projects
Per-directory vimrc that's checked when the file is opened (see below). Another fairly easy one to implement, especially if your project code is all in one place.
Scanning for a Header
In a lot of organisations, there's a standard header (with a copyright notice and project name etc) at the top of every source file. If this is the case, you can get Vim to automatically scan the first (e.g.) 10 lines of the file looking for a keyword. If it finds it, it can change your settings. I've modified this to make it simpler than the form I use (which does lots of other things), but create a ~/.vim/after/filetype.vim (if you don't have one yet) and add something like this:
au FileType * call <SID>ConfigureFiletypes(expand("<amatch>"))
" List of file types to customise
let s:GROUPNAMETypes = ['c', 'cpp', 'vhdl', 'c.doxygen']
func! <SID>CheckForGROUPNAMECode()
" Check if any of the first ten lines contain "GROUPNAME".
" Read the first ten lines into a variable
let header = getline(1)
for i in range(2, 10)
let header = header . getline(i)
endfor
if header =~ '\<GROUPNAME\>'
" Change the status line to make it clear which
" group we're using
setlocal statusline=%<%f\ (GROUPNAME)\ %h%m%r%=%-14.(%l,%c%V%)\ %P
" Do other customisation here
setlocal et
" etc
endif
endfunc
func! <SID>ConfigureFiletypes(filetype)
if index(s:GROUPNAMETypes, a:filetype) != -1
call <SID>CheckForGROUPNAMECode()
endif
endfunc
Whenever a file of any type is opened and the file type is set (the au FileType * line), the ConfigureFiletypes function is called. This checks whether the file type is in the list of file types associated with the current group (GROUPNAME), in this case 'c', 'cpp', 'vhdl' or 'c.doxygen'. If it is, it calls CheckForGROUPNAMECode(), which reads the first 10 lines of the file and if they contain GROUPNAME, it does some customisation. As well as setting expandtabs or whatever, this also changes the status bar to show the group name clearly so you know it's worked at a glance.
Checking for Configuration When Opening
Much like JS Bangs' suggestion, having a custom configuration file can be useful. However, instead of loading it in vimrc, consider something like this, which will check when a .c file is opened for a .vim.custom in the same directory as the .c file.
au BufNewFile,BufRead *.c call CheckForCustomConfiguration()
function! CheckForCustomConfiguration()
" Check for .vim.custom in the directory containing the newly opened file
let custom_config_file = expand('%:p:h') . '/.vim.custom'
if filereadable(custom_config_file)
exe 'source' custom_config_file
endif
endfunction
You can also put autocommands in your .vimrc which set specific options on a per-path basis.
au BufRead,BufNewFile /path/to/project1/* setl sw=4 et
au BufRead,BufNewFile /path/to/project2/* setl sw=3 noet
Plugin doing the right thing:
http://www.vim.org/scripts/script.php?script_id=441
“This plugin searches for local vimrc files in the filesystem tree of the currently opened file. By default it searches for all ".lvimrc" files from the file's directory up to the root directory and loads them in reverse order. The filename and amount of loaded files is customizable through global variables.”
Assuming your fellow developers won't complain about it, you can always add vim settings to each file in the comments.
/*
* vim:ts=4:sw=4:expandtab:...
*/
int main(int argc, char **argv)
{
...
I created an open-sourced tool for just this purpose. Forget the headers, scanning, configurations, and local vimrc files.
Try swim.
Swim
swim is a quick tool for switching vimrc files and creating convenient aliases. Here's a short usage list. See the Github repo for a walkthrough gif and download instructions:
Usage
swim add ~/dotfiles/myVimrc favorite #Add new swim alias
swim ls #Show available swim aliases
swim add https://raw.githubusercontent.com/dawsonbotsford/swim/master/exampleVimrcs/vimrcWikia.vim example
swim with favorite #Set alias favorite as primary .vimrc
swim with main #Set alias main as primary .vimrc
Read More
https://github.com/dawsonbotsford/swim
After trying out the localvimrc plugin suggested by the previous poster, I very much like having non-futzy per-project control over vim settings.
It does ask confirmation before loading a .lvimrc file by default but there is a setting to automatically load .lvimrc files. Some might see this as a security hole, but it works as advertised.
I chose to .gitignore the .lvimrc files. Alternatively you can check them in as a form of shared settings (tab/space expansion, tabstops, other project-specific settings).
As mentioned by sledge the usage of that plug-in is the best option I have seen and use. jerseyboy commented that the utility recommended ask for confirmation before loading (ie. after opening every file). To avoid this just set at your main .vimrc the list of local .lvimrc files:
let g:localvimrc_whitelist='/development/kernel/.lvimrc'
Here's a variation on jamessan's
function! ConditionalLoad()
let cwd = getcwd()
if getcwd() =~ $HOME . "/src/mobile"
so $HOME/.vim.mobile
endif
endfunction
autocmd VimEnter * call ConditionalLoad()
I will frequently launch vi without a specific file that I'm jumping to so this enables loading config conditionally based on the current working directory. Downside is that the config isn't applied based on file but off of working directory.
I work in several groups, each of which has its own tab/indentation/spacing standards in C.
I work with all sorts of open source, all at the same time. It's not practical to be creating separate .vimrc files and reconfiguring the formatting standards. More than a decade ago, I finally got tired of dealing with the editor configuration and wrote a program called autotab to handle it.
When autotab is set up with Vim suggested, each time you load a file into Vim, autotab is invoked on it, and the Vim settings output autotab are passed to a :set command.
autotab reads several thousand lines from the file, analyzes them and determines the settings for the expandtab, tabstop and shiftwidth parameters.
It figures out whether the file uses hard tabs or just spaces for indentation, and it figures out the indentation size. If the file is indented with tabs, it figures out the right tab size, based on rendering the file sample using various tab sizes and judging it according to heuristics like line-over-line alignment of internal elements.
It works well enough that I stopped tweaking the algorithm years ago. If it gets confused, it's almost always because the file has formatting issues, such as the use of multiple conventions at the same time.
It is also "agnostic" of the file type and works well with a variety of different languages. I use it not only over C, but shell scripts, Lisp, Makefiles, HTML, and what have you.
Note that it doesn't handle other parameters of formatting that may be project-specific, like for instance, in C files, whether case labels in a switch statement are indented or not, or whether wrapped function argument lists are simply indented, or aligned to the opening parenthesis of the argument list. Vim does have settings for that sort of thing, and so the program could be plausibly extended to analyze the style and output those parameters.
Looking for mostly the same issue I also found the Sauce plug-in: http://www.vim.org/scripts/script.php?script_id=3992
It claims:
Sauce is a lightweight manager for multiple vimrc files, which can be used to load different settings for different environments. In short, you can maintain lots of different vim settings files and only load the one(s) you need when you need them.
I find it particularly interesting that it keeps it configuration all in its data directory instead of expecting the user to sprinkle dotfiles across the filesystem. This though often rather a metter of personal taste.
I have yet to test it though.
You can use stow for switching configuration (any dotfiles, not only .vimrc)
Install stow:
$ apt install stow
Create multiple directories for each configurations:
~$ ls -d ~/dotfiles/vim*
vim-all vim-webdev vim-go
Put different .vimrc's in them:
$ find ~/dotfiles -name .vimrc
/home/username/vim-golang/.vimrc
/home/username/vim-webdev/.vimrc
/home/username/vim-all/.vimrc
Now you can instantinate vim-golang config with this command (should be run inside dotfiles directory):
~$ cd ~/dotfiles
dotfiles$ stow -v vim-golang
LINK: .vimrc => dotfiles/vim-golang/.vimrc
Now it's linked:
$ cd ~ && ls -l .vimrc
.vimrc -> dotfiles/vim-golang/.vimrc
If you need to switch config, just re-stow it:
~$ cd dotfiles
dotfiles$ stow -v -D vim-golang
UNLINK: .vimrc
dotfiles$ stow -v vim-webdev
LINK: .vimrc => dotfiles/vim-webdev/.vimrc
$ cd ~ && ls -l .vimrc
.vimrc -> dotfiles/vim-webdev/.vimrc
More reading of it here: Managing dotfiles with GNU stow
Pros: pretty simple, no vim plugin dependencies, can be used for managing all dotfiles, not only .vimrc.
Cons: configs are independent of each other, you need to manage/update each of them separately (if you dont switch/update you configs too often - it'll not be the issue).

How to implement own tag jump in VIM with CTRL-]?

If :h is used in VIM, it will automaticall follow |links| via CTRL+], opening new help topics and maintaining tag jumps list (CTRL+T will go back in jumps history). How to implement such behavior in my own file format? For example, i want CTRL+] on text inside {} to open a file named something.txt and CTRL+T to go back. How to implement this?
It's all done with tags. Essentially the vim files are simple text files, but they're supported by a file in the same directory named 'tags'. All this file contains is entries that look like:
'bg' options.txt /*'bg'*
'bh' options.txt /*'bh'*
'bin' options.txt /*'bin'*
'binary' options.txt /*'binary'*
'biosk' options.txt /*'biosk'*
'bioskey' options.txt /*'bioskey'*
Each line is a tag entry, split over three fields: the tag identifier, the file the tag lives in, and the ex command to find that tag: any ex command works; as can be seen in the example above though, the vim help files just use the search command: '/'.
You can either write a tags file manually, or use a program such as Exuberent ctags to create the file automatically. The tags file is generally read from the same directory the file you're editing lives in, but you can change this in Vim by adjusting the value of the 'tags' option.
More details in vim if you type ":help tags"

Resources