Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make vim follow symlinks when opening files from command line

Tags:

linux

vim

macos

zsh

I'm a huge vim lover, but I can't find a way to get vim to follow symlinks when opening files.

As an example, all the dotfiles in my home dirs are symlinked to within the .zprezto directory:

.vimrc -> ~/.zprezto/runcoms/vimrc
.zshrc -> ~/.zprezto/runcoms/zshrc

I'm keeping my fork of .zprezto in a private git repo, which is then used to keep all my Mac/Linux machines and servers in sync. Whenever I'm editing any of these files in vim, none of the plugins I'm using for git management work properly, because the symlink I'm accessing when calling vim ~/.zshrc is outside the git repo. Is there any way of forcing vim to follow the link and open up the actual file when I open it from the command line, so that the buffer is then in the git repo?

Tried this:

function vim() {
  local ISLINK=`readlink $1`
  /usr/local/bin/vim ${ISLINK:-$1}
}

but it didn't work as well as I'd hoped as it limits me to one file with no options. I'd like to know if there's a more sensible way of doing this before I go about write a massive wrapper function that can take all edge cases into account.

like image 967
James Dinsdale Avatar asked Jun 11 '15 21:06

James Dinsdale


People also ask

Which command follows symlinks?

In order to follow symbolic links, you must specify ls -L or provide a trailing slash. For example, ls -L /etc and ls /etc/ both display the files in the directory that the /etc symbolic link points to. Other shell commands that have differences due to symbolic links are du, find, pax, rm and tar.

How do I create a symbolic link between two files?

To create a symbolic link, use the -s ( --symbolic ) option. If both the FILE and LINK are given, ln will create a link from the file specified as the first argument ( FILE ) to the file specified as the second argument ( LINK ).

Does du follow symlinks?

The -L option tells du to process symbolic links by using the file or directory which the symbolic link references, rather than the link itself.

How does Symlinks work in Linux?

A symlink is a symbolic Linux/ UNIX link that points to another file or folder on your computer, or a connected file system. This is similar to a Windows shortcut. Symlinks can take two forms: Soft links are similar to shortcuts, and can point to another file or directory in any file system.


1 Answers

So it doesn't look like there's anything built into vim to allow this. I had a play with the wrapper function and it turned out to be a little easier than I thought. Here's the final result:

function vim() {
  args=()
  for i in $@; do
    if [[ -h $i ]]; then
      args+=`readlink $i`
    else
      args+=$i
    fi
  done

  /usr/local/bin/vim -p "${args[@]}"
}

Just add to your .zshrc (or config file for your favorite shell) to use it.

like image 160
James Dinsdale Avatar answered Nov 16 '22 03:11

James Dinsdale