Skip to content

Commit 7c4617a

Browse files
committed
1 parent 559db22 commit 7c4617a

File tree

7 files changed

+387
-232
lines changed

7 files changed

+387
-232
lines changed

autoload/pymode/rope.vim

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -53,16 +53,11 @@ endfunction
5353

5454

5555
fun! pymode#rope#find_it()
56-
let l:output = []
56+
let loclist = g:PymodeLocList.current()
57+
let loclist._title = "Occurrences"
5758
call pymode#wide_message('Finding Occurrences ...')
5859
PymodePython rope.find_it()
59-
call pymode#wide_message('')
60-
if !empty(l:output)
61-
let loclist = g:PymodeLocList.current()
62-
let loclist._loclist = l:output
63-
let loclist._title = "Occurrences"
64-
call loclist.show()
65-
end
60+
call loclist.show()
6661
endfunction
6762

6863

pymode/environment.py

Lines changed: 242 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,242 @@
1+
""" Define interfaces. """
2+
3+
from __future__ import print_function
4+
5+
import vim
6+
import json
7+
import time
8+
import os.path
9+
10+
from .utils import PY2
11+
12+
13+
class VimPymodeEnviroment(object):
14+
15+
""" Vim User interface. """
16+
17+
prefix = '[Pymode]'
18+
19+
def __init__(self):
20+
self.current = vim.current
21+
self.options = dict(encoding=vim.eval('&enc'))
22+
self.options['debug'] = self.var('g:pymode_debug', True)
23+
24+
@property
25+
def curdir(self):
26+
""" Return current working directory. """
27+
28+
return self.var('getcwd()')
29+
30+
@property
31+
def curbuf(self):
32+
""" Return current buffer. """
33+
34+
return self.current.buffer
35+
36+
@property
37+
def cursor(self):
38+
""" Return current window position.
39+
40+
:return tuple: (row, col)
41+
42+
"""
43+
return self.current.window.cursor
44+
45+
@property
46+
def source(self):
47+
""" Return source of current buffer. """
48+
49+
return "\n".join(self.lines)
50+
51+
@property
52+
def lines(self):
53+
""" Iterate by lines in current file.
54+
55+
:return list:
56+
57+
"""
58+
if not PY2:
59+
return self.curbuf
60+
61+
return [l.decode(self.options.get('encoding')) for l in self.curbuf]
62+
63+
def var(self, name, to_bool=False):
64+
""" Get vim variable.
65+
66+
:return vimobj:
67+
68+
"""
69+
70+
value = vim.eval(name)
71+
72+
if to_bool:
73+
try:
74+
value = bool(int(value))
75+
except ValueError:
76+
value = value
77+
return value
78+
79+
def message(self, msg, history=False):
80+
""" Show message to user. """
81+
82+
if history:
83+
return vim.command('echom "%s"' % str(msg))
84+
85+
return vim.command('call pymode#wide_message("%s")' % str(msg))
86+
87+
def user_input(self, msg, default=''):
88+
""" Return user input or default.
89+
90+
:return str:
91+
92+
"""
93+
msg = '%s %s ' % (self.prefix, msg)
94+
95+
if default != '':
96+
msg += '[%s] ' % default
97+
98+
try:
99+
vim.command('echohl Debug')
100+
input_str = vim.eval('input("%s> ")' % msg)
101+
vim.command('echohl none')
102+
except KeyboardInterrupt:
103+
input_str = ''
104+
105+
return input_str or default
106+
107+
def user_confirm(self, msg, yes=False):
108+
""" Get user confirmation.
109+
110+
:return bool:
111+
112+
"""
113+
default = 'yes' if yes else 'no'
114+
action = self.user_input(msg, default)
115+
return action and 'yes'.startswith(action)
116+
117+
def user_input_choices(self, msg, *options):
118+
""" Get one of many options.
119+
120+
:return str: A choosen option
121+
122+
"""
123+
choices = ['%s %s' % (self.prefix, msg)]
124+
choices += [
125+
"%s. %s" % (num, opt) for num, opt in enumerate(options, 1)]
126+
try:
127+
input_str = int(
128+
vim.eval('inputlist(%s)' % self.prepare_value(choices)))
129+
except (KeyboardInterrupt, ValueError):
130+
input_str = 0
131+
132+
if not input_str:
133+
self.message('Cancelled!')
134+
return False
135+
136+
try:
137+
return options[input_str - 1]
138+
except (IndexError, ValueError):
139+
self.error('Invalid option: %s' % input_str)
140+
return self.user_input_choices(msg, *options)
141+
142+
def error(self, msg):
143+
""" Show error to user. """
144+
vim.command('call pymode#error("%s")' % str(msg))
145+
146+
def debug(self, msg, *args):
147+
""" Print debug information. """
148+
149+
if self.options.get('debug'):
150+
print("%s %s [%s]" % (
151+
int(time.time()), msg, ', '.join([str(a) for a in args])))
152+
153+
def stop(self, value=None):
154+
""" Break Vim function. """
155+
156+
cmd = 'return'
157+
if value:
158+
cmd += ' ' + self.prepare_value(value)
159+
vim.command(cmd)
160+
161+
def catch_exceptions(self, func):
162+
""" Decorator. Make execution more silence.
163+
164+
:return func:
165+
166+
"""
167+
168+
def _wrapper(*args, **kwargs):
169+
try:
170+
return func(*args, **kwargs)
171+
except (Exception, vim.error) as e: # noqa
172+
if self.options.get('debug'):
173+
raise
174+
self.error(e)
175+
return None
176+
return _wrapper
177+
178+
def run(self, name, *args):
179+
""" Run vim function. """
180+
181+
vim.command('call %s(%s)' % (name, ", ".join([
182+
self.prepare_value(a) for a in args
183+
])))
184+
185+
def let(self, name, value):
186+
""" Set variable. """
187+
cmd = 'let %s = %s' % (name, self.prepare_value(value))
188+
self.debug(cmd)
189+
vim.command(cmd)
190+
191+
def prepare_value(self, value):
192+
""" Decode bstr to vim encoding.
193+
194+
:return unicode string:
195+
196+
"""
197+
198+
value = json.dumps(value)
199+
if PY2:
200+
value = value.decode('utf-8').encode(self.options.get('encoding'))
201+
202+
return value
203+
204+
def get_offset_params(self, cursor=None, base=""):
205+
""" Calculate current offset.
206+
207+
:return tuple: (source, offset)
208+
209+
"""
210+
row, col = cursor or env.cursor
211+
source = ""
212+
offset = 0
213+
for i, line in enumerate(self.lines, 1):
214+
if i == row:
215+
source += line[:col] + base
216+
offset = len(source)
217+
source += line[col:]
218+
else:
219+
source += line
220+
source += '\n'
221+
env.debug('Get offset', base or None, row, col, offset)
222+
return source, offset
223+
224+
def goto_line(self, line):
225+
""" Go to line. """
226+
227+
vim.command('normal %sggzz' % line)
228+
229+
def goto_file(self, path, cmd='e', force=False):
230+
""" Function description. """
231+
232+
if force or os.path.abspath(path) != self.curbuf.name:
233+
self.debug('read', path)
234+
vim.command("%s %s" % (cmd, path))
235+
236+
def goto_buffer(self, bufnr):
237+
""" Open buffer. """
238+
if str(bufnr) != '-1':
239+
vim.command('buffer %s' % bufnr)
240+
241+
242+
env = VimPymodeEnviroment()

pymode/lint.py

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
""" Pylama integration. """
22

3-
import vim # noqa
4-
from .utils import pymode_message, silence_stderr
3+
from .environment import env
4+
from .utils import silence_stderr
55

66
import os.path
77

@@ -15,31 +15,27 @@ def code_check():
1515

1616
from pylama.main import parse_options
1717
from pylama.tasks import check_path
18-
import json
19-
20-
b = vim.current.buffer
21-
root = vim.eval('getcwd()')
22-
linters = vim.eval('g:pymode_lint_checkers')
23-
ignore = vim.eval('g:pymode_lint_ignore')
24-
select = vim.eval('g:pymode_lint_select')
2518

2619
options = parse_options(
27-
ignore=ignore, select=select, linters=linters)
20+
ignore=env.var('g:pymode_lint_ignore'),
21+
select=env.var('g:pymode_lint_select'),
22+
linters=env.var('g:pymode_lint_checkers'),
23+
)
2824

29-
path = b.name
30-
if root:
31-
path = os.path.relpath(path, root)
25+
path = os.path.relpath(env.curbuf.name, env.curdir)
26+
env.debug("Start code check: ", path)
3227

3328
if getattr(options, 'skip', None) and any(p.match(path) for p in options.skip): # noqa
34-
pymode_message('Skip code checking.')
35-
vim.command('return')
29+
env.message('Skip code checking.')
30+
env.debug("Skipped")
31+
env.stop()
3632
return False
3733

38-
code = '\n'.join(vim.current.buffer)
39-
4034
with silence_stderr():
41-
errors = check_path(path, options=options, code=code)
42-
sort_rules = vim.eval('g:pymode_lint_sort')
35+
errors = check_path(path, options=options, code=env.source)
36+
37+
env.debug("Find errors: ", len(errors))
38+
sort_rules = env.var('g:pymode_lint_sort')
4339

4440
def __sort(e):
4541
try:
@@ -48,10 +44,10 @@ def __sort(e):
4844
return 999
4945

5046
if sort_rules:
47+
env.debug("Find sorting: ", sort_rules)
5148
errors = sorted(errors, key=__sort)
5249

5350
for e in errors:
54-
e['bufnr'] = b.number
51+
e['bufnr'] = env.curbuf.number
5552

56-
vim.command(
57-
'call g:PymodeLocList.current().extend(%s)' % json.dumps(errors))
53+
env.run('g:PymodeLocList.current().extend', errors)

0 commit comments

Comments
 (0)