How to easily delete swap file placed in another directory (vim)? - vim

I had a session with 7 files opened in vim. After accidental crash and reloading the session each file gives E325: ATTENTION explaining that the files are newer than swap ones! I don't remember how these files become newer that the original swap ones, but for now it doesn't matter, because I want to learn how to handle this case.
I think, the solution would be simple if swap files was placed along the files itself (eg .filename.swp next to filename). Because I could remove it just by :!rm .%.swp.
However I changed the default directory of swap files, which is now set to directory=~/.vim/tmp/swp//. So the question is how can I get the full pathname to the swap file. For example:
vim /home/timur/code/src/project/main.go
E325: ATTENTION
...
Swap file "~/.vim/tmp/swp//%home%timur%code%src%project%main.go.swp" already exists!
[O]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort
E or R
After I opened the buffer I want to type something like this:
:remove *swapname*
or using a shortcut:
<leader>rw
I've read the docs and found the command to show current swap file name: :swapname. But it seems the output name isn't fit to passing it into rm command, because there is additional slash before the swap name. For example:
Actual file:
/home/timur/.vim/tmp/swp/%home%timur%code%own%src%file
The output of :swapname (adds odd slash before swap name)
/home/timur/.vim/tmp/swp//%home%timur%code%own%src%file.swp
^ ???
To put it simple: how to get direct/explicit path to swap file of current buffer?

Inspired by issue 355, here is your mapping
nnoremap <silent> <Leader>rw :call DeleteSwapFile()<CR>
function! DeleteSwapFile()
redir => s:a
exe ':sil sw'
redir end
let b:swapname = s:a[1:]
call delete(b:swapname)
endfunction
:h redir

If you don't mind solving the problem using a vim plugin try Recover.vim plugin.
When opening a new file, it checks if a swapfile is already present.
If so gives two additionals options:
[D]elete: delete the swapfile (i use this option very rarely)
D(i)ff: compare the recover version of the file and the current version. If they are the same it asks you if you want to delete the swap file. If they are not the same open a vimdiff session between to visually compare the differences.
Really a must have.

Related

vim: recovering a text file "already at oldest change"

I am using vim to edit .sh file. Last time, I was making changes I got: "E297: Write error in swap file" and I accidentally managed to erase the content and save.
Now, all I have is .sh .sh~ .su~ .sv~ .sw~ .sy~ .sz~ files with empty content and "E297: Write error in swap file" message. When I do :u, it says: "already at oldest change".
when I do :recover, it says: "E305: no swap file found"
How to recover my file? thanks
In this case, the original file may be recovered using swap files which have the form .filename.sh.swp. These are files that Vim creates to back up in case of a potential crash. In order to recover your original file, try these steps:
Look for swap files in the current directory (there could be more than one for a particular file):
ls -a
Open the first swap file in Vim from the terminal:
vi .filename.sh.swp
or alternatively, launch Vim with vim and edit the swap file with :e .filename.sh.swp.
From within the swap file type :recover. Now Vim will load the recovered file on a new buffer. If this is the file that you needed then simply save the file :w.
It could be that the recovered file is not exactly the latest version of your filename.sh, in this case repeat steps 2 and 3 above with a different swap file e.g. .filename.sh.swo. Once the desired file has been recovered removed the swap files.
These help pages are also relevant for recovering files:
:help swap
:help recover
:help e305

Make VIM to consider current folder the root

I already know how to quit Vim, now I'm wondering is it possible anyhow to force Vim search '/somedir/file.js' in current directory when you press gf, as if it were './somedir/file.js'?
UPD: There's question how to set path in general, but it doesn't help to make /myfolder/ pointed to some certain folder I want. /myfolder/ is always absolute path to the root of current volume.
Vim counts filenames beginning with / as file system root always, as
you observed. If that wasn't the case, of if 'isf' (the option that
controls what is considered file name) accepted a regex, this would be
easier to solve. But if you remove / from 'isf' then no slashes are
considered part of a file name anymore.
The only solution to this I can think of is using the visual mode for
gf. As you may know, if you have text selected visually and use gf
then the visual selection will be considered, instead of the 'isf'
match. Then all we need to do is to visually select the file name under
cursor excluding a possible leading /. This can be solved in a map, if
you don't mind messing your previous search:
nnoremap <silent> gf :let #/ = substitute(expand('<cfile>'), '^/', '', '')
\ <bar>normal gngf<cr>
This overwrites your gf to set the search to the filename under cursor
(expand()), minus leading slash if any (substitute()) and then run
the normal commands gn which selects the match and finally the
original gf.
If you want to save your previous search and restore, you can easily
create a function to wrap this all. Note that I also wrote this is two
lines just because I'm a declared enemy of long lines. But if you just
want to test it remove the \ and write in a single line.
Now your gf will interpret /file as file. Thus if you're on the
correcty directory this will work. If you need to search in a different
directory, the option you're looking for is 'path', or 'pa' for
short. You can give a list of directories to search. Much like Unix
shell's $PATH. Separated by commas. From the help (be sure to read the
rest yourself, with :h 'pa):
This is a list of directories which will be searched when using the
gf, [f, ]f, ^Wf, :find, :sfind, :tabfind and other
commands, provided that the file being searched for has a relative
path (not starting with "/", "./" or "../"). The directories in the
'path' option may be relative or absolute.
In conclusion, to use this in your project, set your 'path' if needed
as you wish and enable this map. Or run it all automatically in a
:autocmd or something similar. You aren't changing the root of the
project as you initially suggested, but you're kind of emulating this by
including the desired directory in 'path' and then forcing gf to
ignore the leading /.

How to get the value of the current swap directory in vimscript?

You can set a list of directories for vim to use for the swapfile (with it defaulting to the first one it can find) with:
set directory=~/tmp,~/var/tmp,/var/tmp,/tmp
I want to know which directory vim has chosen for its swapfile so I can stick some temp data in there.
Parsing &directory and looping through the values seems like a waste when vim should have already figured that out.
The :swapname command will tell you which swapfile is used for the current buffer. You need to use :redir => varname to capture the output and store it in a variable.
I think the "used" directory is not saved somewhere by vim, like a variable or something. It could be different from buffer to buffer. (from file to file).
e.g.
you have a non-root user. say kent, his directory setting is:
set directory=.,~/tmp,/var/tmp,/tmp
now kent opens /etc/host.conf in his vim, and editing. the first .(dot) means current dir. obviously kent cannot write file to /etc, so take the 2nd ~/tmp, but kent doesn't have tmp under his home, so next, /var/tmp is used.
if kent opens a file under his HOME, or under /tmp, for example, the .(dot) would be used. And note that the dot for different files are different.
kent can open many files in buffers, so it is hard to say, which dir would be used for swap files.
so the swapfile - dir is not fixed to a directory. you should check it based on the buffer/file.
If you do this often, I suggest to write a function:
function! SwapDirectoryForCurrentFile()
redir => filename
silent! swapname
redir end
return fnamemodify(filename, ":h")
endfunction

Vim ignore pathname in file completion

Let's say I'm in /tmp and I have two files open in vim: test.txt and tmpfile.txt. Now I want to remove the tmpfile.txt buffer. I type :bd tmTAB. The behavior I want is for it to autocomplete tmpfile.txt; the behavior I get is a list of tmpfile.txt and /tmp/test.log, as it's autocompleting on the directory name as well as the filename. How can I make vim behave like I want?
Use ^tm instead to match at the beginning of the file name. (You have to be in /tmp for this to work so that the relative path is just the filename.)
That is not possible, the list comes from what's on the buffer list, not from your local path, you could be at any place (:pwd), it doesn't matter, when you press tab the result comes from the in memory list, thats why /tmp appears because if you're on /tmp, /tmp shouldn't appear again.
if you look at :help :bd it takes bufname as param, not fname as :badd

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).

Resources