I am making a Vim (Neovim) plugin by referring to the article linked above. When the Python file got bigger and I tried to split it, I stumbled a bit so I'll share the solution.
In this article, as an example, let's create a plugin that displays the title of a web page using the requests module.
sample-vim-plugin
plugin/
sample_vim_plugin.vim
src/
sample_vim_plugin.py
requests_caller.py
plugin/sample_vim_plugin.vim
scriptencoding utf-8
if exists('g:loaded_sample_vim_plugin')
finish
endif
let g:loaded_sample_vim_plugin = 1
let s:save_cpo = &cpo
set cpo&vim
py3file <sfile>:h:h/src/sample_vim_plugin.py
function! sample_vim_plugin#print_title(url)
py3 sample_vim_plugin_print_title(vim.eval('a:url'))
endfunction
let &cpo = s:save_cpo
unlet s:save_cpo
src/sample_vim_plugin.py
import vim
import requests_caller
def sample_vim_plugin_print_title(url):
print(requests_caller.get_title(url))
requests_caller.py
import requests
from bs4 import BeautifulSoup
def get_title(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')
return soup.title.text
I manage plugins with dein, so when I add the above plugin to the toml file and start neovim
ModuleNotFoundError: No module named 'requests_caller'
It is said that.
I would like to solve the problem that this module cannot be found.
In "Processing'runtimepath'in Python"
In Python, instead of using the list of paths for'runtimepath', vim.VIM_SPECIAL_PATH A special directory called is used. This directory is used in sys.path When, and when vim.path_hooks is used within sys.path_hooks,'runtimepath' {Rtp} / python2 (or python3) and {rtp} / pythonx (both bars) for each path {rtp} in The module (loaded by John) will be loaded.
There is.
Therefore, there are two possible methods.
It is said that if there are python2, python3, pythonx directories directly under the runtime path, it will be loaded, so rename the src directory to python3. Of course it is necessary to change the part to be read, so change it as follows
plugin/sample_vim_plugin.vim
- py3file <sfile>:h:h/src/sample_vim_plugin.py
+ py3file <sfile>:h:h/python3/sample_vim_plugin.py
If you don't want to rename the directory, add it directly to sys.path.
plugin/sample_vim_plugin.vim
+ let s:sample_vim_plugin_root_dir = expand('<sfile>:p:h:h')
py3file <sfile>:h:h/src/sample_vim_plugin.py
src/sample_vim_plugin.py
import vim
+ import sys
+ import os
+ plugin_python_dir = os.path.join(vim.eval('s:sample_vim_plugin_root_dir'), 'src')
+ sys.path.append(plugin_python_dir)
import requests_caller
--Put Python files in python2, python3, pythonx directories --Add the directory containing the Python files to sys.path
The plug-in will work in two ways.
Well-known, davidhalter / jedi-vim seems to use Solution 1 (pythonx). I just glanced at the source code, but Shougo / denite.nvim and Shougo / deoplete.nvim seems to use solution 2.
Recommended Posts