Skip to content

Commit df1cfba

Browse files
Simple VIM plugin in python
0 parents  commit df1cfba

2 files changed

Lines changed: 86 additions & 0 deletions

File tree

myplugin/plugin/myplugin.vim

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
" myplugin.vim
2+
3+
let current_dir = expand('<sfile>:p:h')
4+
let relative_path = '../python'
5+
let g:myplugin_python_dir = resolve(current_dir . '/' . relative_path)
6+
set rtp+=myplugin_python_dir
7+
8+
9+
function! CallPythonFunction(command_name, module_name, ...)
10+
python3 << EOF
11+
import sys
12+
sys.path.append(vim.eval('g:myplugin_python_dir'))
13+
14+
import vim
15+
16+
# Get the function name and arguments from Vim script
17+
args = vim.eval('a:000')
18+
19+
python_args = [*args][0].split(" ")
20+
function_name = python_args[0]
21+
args = python_args[1:]
22+
23+
# Import the module containing the function
24+
module = __import__(module_name)
25+
26+
# Get a reference to the function
27+
function = getattr(module, function_name)
28+
29+
result = function(*args)
30+
31+
# Print the output in a new window
32+
if result != None:
33+
vim.command("split .{}.output | normal Go{}".format(module_name, result))
34+
35+
EOF
36+
37+
endfunction
38+
39+
40+
function! CreatePythonCommands()
41+
python3 << EOF
42+
import vim
43+
import os
44+
import importlib.util
45+
46+
# Get the Python directory from Vim script
47+
python_dir = vim.eval('g:myplugin_python_dir')
48+
49+
# Find all Python modules in the directory
50+
modules = [f for f in os.listdir(python_dir) if f.endswith('.py') and not f.startswith('__')]
51+
module_names = [os.path.splitext(f)[0] for f in modules]
52+
53+
# Create a Vim command for each function in each module
54+
for module_name in module_names:
55+
spec = importlib.util.spec_from_file_location(module_name, os.path.join(python_dir, module_name + '.py'))
56+
module = importlib.util.module_from_spec(spec)
57+
spec.loader.exec_module(module)
58+
functions = [f for f in dir(module) if callable(getattr(module, f))]
59+
60+
command_name = module_name.capitalize()
61+
command_string = 'call CallPythonFunction("' + command_name + '", "' + module_name + '", <q-args>)'
62+
command = 'command! -nargs=* ' + command_name + ' :execute \'' + command_string + '\''
63+
print(command)
64+
vim.command(command)
65+
EOF
66+
endfunction
67+
68+
69+
" Create Vim commands for the functions in the modules
70+
call CreatePythonCommands()

myplugin/python/mymodule.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import vim
2+
3+
def foo():
4+
vim.command("normal! i>> ")
5+
vim.command("normal! iHello!")
6+
return "Hello World!\n\n"
7+
8+
def bar(x, y):
9+
return str(int(x) + int(y))
10+
11+
def none():
12+
print('ok')
13+
return None
14+
15+
def nothing():
16+
print('ok')

0 commit comments

Comments
 (0)