amoffat / snake Goto Github PK
View Code? Open in Web Editor NEWFull Python Scripting in Vim
Full Python Scripting in Vim
Hey, I'm wondering if you are going to continue working on snake. I just upgraded to 3.11 and noticed that changes to open() (the "U" flag has gone away) is causing a failure:
Error invoking 'python_execute_file' on channel 3 (python3-script-host):
Traceback (most recent call last):
File "/home/badger/.vim/pack/badger/start/snake/plugin/bootstrap.py", line 11, in <module>
import snake
File "/home/badger/.vim/pack/badger/start/snake/plugin/snake/__init__.py", line 737, in <module>
from . import plugin_loader
File "/home/badger/.vim/pack/badger/start/snake/plugin/snake/plugin_loader.py", line 215, in <module>
import_source("vimrc", vimrc_path)
File "/home/badger/.vim/pack/badger/start/snake/plugin/snake/plugin_loader.py", line 206, in import_s
ource
h = open(path, desc[1])
^^^^^^^^^^^^^^^^^^^
ValueError: invalid mode: 'U'
If you're going to continue work on snake, I can look at opening a PR to omit the flag when we are using later python versions. There are other deprecations in the works, though (for instance, imp is deprecated) so I'll probably try porting my configs to lua if you don't have time to keep snake updated anymore.
vim version 7.4
sh is installed
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 14.04.3 LTS
Release: 14.04
Codename: trusty
output:
Despite having python3 support added in 29707b2, there is still a hardcoded preference for python2. I fail to see how this behavior can be useful.
Since I don't see you making a preference for python3 instead (I would love that, of course, just as I would love to magically see the world completely forget python2 in an instant, but I suppose that's not gonna happen), I would like to see at least a switch implemented somewhere.
set clipboard=unnamed
makes vim play nice with OS X; however, it changes yank behavior such that vim isn't using the registers that get_register
expects. I haven't come up with an alternative yet, so I'm hoping someone else has an idea (and hence, the ticket.)
When I updated setuptools to 61.2.0
, this error is shown every time I start vim.
I figured out it was because the command import virtualenv
caused this warning message.
Error detected while processing function LoadSnake:
line 9:
/home/myuser/.local/lib/python3.8/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other
standards-based tools.
warnings.warn(
Press ENTER or type command to continue
Other message is also shown but I didn't figure out where it was caused.
/home/myuser/.local/lib/python3.8/site-packages/_distutils_hack/__init__.py:30: UserWarning: Setuptools is replacing distutils.
warnings.warn("Setuptools is replacing distutils.")
For now, I inserted warning filter like below.
import warnings
warnings.filterwarnings("ignore")
Ok, so I created 1337repos and randomly visited it today.
I saw snake
and I guess deep down I wished it was related to Metal Gear. I was not disappointed.
The gif, the jokes, the references, everything!
Good work and good luck with this awesome tool. I hope you all the best.
also, sorry for spam/non-issue
for example i map this to insert an code snippet:
@key_map("coco")
def cocoCreate():
#in this function how insert code in File?
I tried to implement a custom text object, but couldn't use key_map
for the vmode part, as it always messes with the visual mode selection. It would be could if there was a keyword argument to disable the special vmode handling.
After install i tryed the <leader>r code from the readme file, when i type \r i get this error:
Erreur détectée en traitant :
E121: Variable non définie : mapleader
E15: Expression invalide : mapleader
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/user/.vim/bundle/snake/plugin/snake/__init__.py", line 54, in dispatch_mapped_function
return fn()
File "/home/user/.vimrc.py", line 5, in reverse
replace_word(get_word()[::-1])
File "/home/user/.vim/bundle/snake/plugin/snake/__init__.py", line 211, in wrapper
return fn(*args, **kwargs)
File "/home/user/.vim/bundle/snake/plugin/snake/__init__.py", line 334, in get_word
keys("yiw")
File "/home/user/.vim/bundle/snake/plugin/snake/__init__.py", line 313, in keys
k = _LEADER_REGEX.sub(get_leader(), k)
File "/home/user/.vim/bundle/snake/plugin/snake/__init__.py", line 304, in get_leader
return vim.eval("mapleader")
vim.error: expression invalide
Replacing contents in visual block selection mode is not working as expected when returning contents from a function decorated with @snake.visual_key_map
.
Example,
.vimrc.py
import snake
def _try_int(text):
try:
val = int(text)
return val
except ValueError:
return 0
def format_numbers(numbers):
max_number = max(numbers)
no_of_digits_in_max_no = len(str(max_number))
format_string = '%{}d'.format(no_of_digits_in_max_no)
return [format_string % no for no in numbers]
@snake.visual_key_map("<leader>fmt")
def align_numbers(selected_snippet):
selected_numbers = selected_snippet.split('\n')
numbers = [_try_int(no) for no in selected_numbers]
return '\n'.join(format_numbers(numbers))
Given file:
Score: 1
Score: 2
Score: 3
Score: 4
Score: 5
Score: 6
Score: 7
Score: 8
Score: 9
Score: 10
Score: 100
After selecting the number block and pressing <leader>fmt
Result:
Score: 1
2
3
4
5
6
7
8
9
10
100
Score:
Score:
Score:
Score:
Score:
Score:
Score:
Score:
Score:
Score:
Expected:
Score: 1
Score: 2
Score: 3
Score: 4
Score: 5
Score: 6
Score: 7
Score: 8
Score: 9
Score: 10
Score: 100
I wanted a way to call Python functions through vim commands, and I have wrote one helper function in my .vimrc.py
,
def command_map(command, nargs="*"):
def decorator(func):
def wrapper(*args):
args = snake.vim.eval("a:000")
return func(*args)
wrapper_func = snake.register_fn(wrapper)
function_name = f"Snake_{func.__name__}"
snake.command(
f"""
function! {function_name}(...)
:{snake.PYTHON_CMD} {wrapper_func}
endfunction
"""
)
snake.command(
f"command! -nargs={nargs} {command} call {function_name}(<f-args>)"
)
return wrapper
return decorator
@command_map("Pwf")
def copy_current_file_path(*args, **kwargs):
current_buffer = snake.vim.current.buffer
if current_buffer.name is None:
snake_echo("No file loaded in current buffer")
else:
pyperclip.copy(current_buffer.name)
snake_echo(current_buffer.name)
Do you think this feature could get into the core? I would like to contribute with a PR if you wish.
Vim already has built-in support for Python scripting, when compiled with the +python
feature. People who find this repository might not know that. You should mention it so that people know what the options are, and describe the differences.
I presume that these are some differences:
python
program to be installed, while built-in support requires Vim to be compiled with +python
. Each prerequisite might be easier to satisfy on some systems and harder on others.If you didn’t know about Vim’s built-in Python support, here is a good tutorial. And here is an example script:
insertbuffername.vim
if !has('python')
finish
endif
function! InsertBufferName()
pyfile insertbuffername.py
endfunc
command! InsertBufferName call InsertBufferName()
insertbuffername.py
def normal(str):
vim.command("normal! "+str)
buffer = vim.current.buffer
normal("i" + buffer.name)
https://travis-ci.org/amoffat/snake/builds/62934759
Can't reproduce this failure locally using same version of Vim and Python. Any help would definitely be appreciated
11.22s$ python tests.py
...........F.........FE......
======================================================================
ERROR: test_let (__main__.VariableTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests.py", line 398, in test_let
self.assertEqual(output["original"], None)
TypeError: 'NoneType' object has no attribute '__getitem__'
======================================================================
FAIL: test_abbrev_fn (__main__.Tests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests.py", line 173, in test_abbrev_fn
self.assertEqual(changed, "1 2\n")
AssertionError: u'\n' != '1 2\n'
======================================================================
FAIL: test_set_buffer_contents (__main__.Tests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests.py", line 150, in test_set_buffer_contents
self.assertEqual(changed, "new stuff")
AssertionError: u'The quick brown fox jumps over the lazy dog' != 'new stuff'
----------------------------------------------------------------------
Ran 29 tests in 11.116s
FAILED (failures=2, errors=1)
it would be nice to have a knob to make snake use python 3 engine, or at least a separate branch with python 3 support (as in intelfx/snake@0085142).
Or, even better, make it use python 3 by default (sweet dreams of a legacy-free world).
just as there is a key_map
decorator it would be great if there was a decorator for things like:
:autocmd CursorMoved * call MyPythonFunc()
Is that feasible?
I can't find how to define a vim command in docs.
codes should like following
@vim_command("reverse")
def reverse():
replace_word(get_word()[::-1])
and reverse()
invokes when I run :reverse
.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.