How to get path to the current vimscript being executed

Vim

Vim Problem Overview


In my vim plugin, I have two files:

myplugin/plugin.vim
myplugin/plugin_helpers.py

I would like to import plugin_helpers from plugin.vim (using the vim python support), so I believe I first need to put the directory of my plugin on python's sys.path.

How can I (in vimscript) get the path to the currently executing script? In python, this is __file__. In ruby, it's __FILE__. I couldn't find anything similar for vim by googling, can it be done?

Note: I am not looking for the currently edited file ("%:p" and friends).

Vim Solutions


Solution 1 - Vim

" Relative path of script file:
let s:path = expand('<sfile>')

" Absolute path of script file:
let s:path = expand('<sfile>:p')

" Absolute path of script file with symbolic links resolved:
let s:path = resolve(expand('<sfile>:p'))

" Folder in which script resides: (not safe for symlinks)
let s:path = expand('<sfile>:p:h')

" If you're using a symlink to your script, but your resources are in
" the same directory as the actual script, you'll need to do this:
"   1: Get the absolute path of the script
"   2: Resolve all symbolic links
"   3: Get the folder of the resolved absolute file
let s:path = fnamemodify(resolve(expand('<sfile>:p')), ':h')

I use that last one often because my ~/.vimrc is a symbolic link to a script in a git repository.

Solution 2 - Vim

Found it:

let s:current_file=expand("<sfile>")

Solution 3 - Vim

It is worth mentioning that the above solution will only work outside of a function.

This will not give the desired result:

function! MyFunction()
let s:current_file=expand('<sfile>:p:h')
echom s:current_file
endfunction

But this will:

let s:current_file=expand('<sfile>')
function! MyFunction()
echom s:current_file
endfunction

Here's a full solution to OP's original question:

let s:path = expand('<sfile>:p:h')

function! MyPythonFunction()
import sys
import os
script_path = vim.eval('s:path')

lib_path = os.path.join(script_path, '.') 
sys.path.insert(0, lib_path)                                       

import vim
import plugin_helpers
plugin_helpers.do_some_cool_stuff_here()
vim.command("badd %(result)s" % {'result':plugin_helpers.get_result()})

EOF
endfunction

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongfxmonkView Question on Stackoverflow
Solution 1 - VimZenexerView Answer on Stackoverflow
Solution 2 - VimgfxmonkView Answer on Stackoverflow
Solution 3 - VimedthedevView Answer on Stackoverflow