Skip to content

Commit ec87fe3

Browse files
committed
Merge pull request #129 from s0undt3ch/master
Support sourcing `vim` files under `.ropeproject/`
2 parents d6b3a73 + 6b60912 commit ec87fe3

3 files changed

Lines changed: 129 additions & 31 deletions

File tree

autoload/pymode.vim

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,15 @@ fun! pymode#PlaceSigns() "{{{
5555
"
5656
if has('signs')
5757
sign unplace *
58+
59+
if !pymode#Default("g:pymode_lint_signs_always_visible", 0) || g:pymode_lint_signs_always_visible
60+
call RopeShowSignsRulerIfNeeded()
61+
endif
62+
5863
for item in filter(getqflist(), 'v:val.bufnr != ""')
5964
execute printf('silent! sign place 1 line=%d name=%s buffer=%d', item.lnum, item.type, item.bufnr)
6065
endfor
66+
6167
endif
6268
endfunction "}}}
6369

plugin/pymode.vim

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,10 @@ if !pymode#Default("g:pymode_lint", 1) || g:pymode_lint
9999
" OPTION: g:pymode_lint_mccabe_complexity -- int. Maximum allowed complexity
100100
call pymode#Default("g:pymode_lint_mccabe_complexity", 8)
101101

102+
" OPTION: g:pymode_lint_signs_always_visible -- bool. Always show the
103+
" errors ruller, even if there's no errors.
104+
call pymode#Default("g:pymode_lint_signs_always_visible", 0)
105+
102106
" OPTION: g:pymode_lint_signs -- bool. Place error signs
103107
if (!pymode#Default("g:pymode_lint_signs", 1) || g:pymode_lint_signs) && has('signs')
104108

@@ -109,6 +113,12 @@ if !pymode#Default("g:pymode_lint", 1) || g:pymode_lint
109113
sign define E text=EE texthl=Error
110114
sign define I text=II texthl=Info
111115

116+
if !pymode#Default("g:pymode_lint_signs_always_visible", 0) || g:pymode_lint_signs_always_visible
117+
" Show the sign's ruller if asked for, even it there's no error to show
118+
sign define __dummy__
119+
autocmd BufRead,BufNew * call RopeShowSignsRulerIfNeeded()
120+
endif
121+
112122
endif
113123

114124
" DESC: Set default pylint configuration
@@ -175,9 +185,17 @@ endif
175185

176186
if !pymode#Default("g:pymode_rope", 1) || g:pymode_rope
177187

178-
" OPTION: g:pymode_rope_auto_project -- bool. Auto open ropeproject
188+
" OPTION: g:pymode_rope_auto_project -- bool. Auto create ropeproject
179189
call pymode#Default("g:pymode_rope_auto_project", 1)
180190

191+
" OPTION: g:pymode_rope_auto_project_open -- bool.
192+
" Auto open existing projects, ie, if the current directory has a
193+
" `.ropeproject` subdirectory.
194+
call pymode#Default("g:pymode_rope_auto_project_open", 1)
195+
196+
" OPTION: g:pymode_rope_auto_session_manage -- bool
197+
call pymode#Default("g:pymode_rope_auto_session_manage", 0)
198+
181199
" OPTION: g:pymode_rope_enable_autoimport -- bool. Enable autoimport
182200
call pymode#Default("g:pymode_rope_enable_autoimport", 1)
183201

@@ -234,6 +252,15 @@ if !pymode#Default("g:pymode_rope", 1) || g:pymode_rope
234252
return ""
235253
endfunction "}}}
236254

255+
fun! RopeOpenExistingProject() "{{{
256+
if isdirectory(getcwd() . '/.ropeproject')
257+
" In order to pass it the quiet kwarg I need to open the project
258+
" using python and not vim, which should be no major issue
259+
py ropevim._interface.open_project(quiet=True)
260+
return ""
261+
endif
262+
endfunction "}}}
263+
237264
fun! RopeLuckyAssistInsertMode() "{{{
238265
call RopeLuckyAssist()
239266
return ""
@@ -249,6 +276,13 @@ if !pymode#Default("g:pymode_rope", 1) || g:pymode_rope
249276
endif
250277
endfunction "}}}
251278

279+
fun! RopeShowSignsRulerIfNeeded() "{{{
280+
if &ft == 'python'
281+
execute printf('silent! sign place 1 line=1 name=__dummy__ file=%s', expand("%:p"))
282+
endif
283+
endfunction "}}}
284+
285+
252286
" Rope menu
253287
menu <silent> Rope.Autoimport :RopeAutoImport<CR>
254288
menu <silent> Rope.ChangeSignature :RopeChangeSignature<CR>
@@ -270,6 +304,15 @@ if !pymode#Default("g:pymode_rope", 1) || g:pymode_rope
270304
menu <silent> Rope.Undo :RopeUndo<CR>
271305
menu <silent> Rope.UseFunction :RopeUseFunction<CR>
272306

307+
if !pymode#Default("g:pymode_rope_auto_project_open", 1) || g:pymode_rope_auto_project_open
308+
call RopeOpenExistingProject()
309+
endif
310+
311+
if !pymode#Default("g:pymode_rope_auto_session_manage", 0) || g:pymode_rope_auto_session_manage
312+
autocmd VimLeave * call RopeSaveSession()
313+
autocmd VimEnter * call RopeRestoreSession()
314+
endif
315+
273316
endif
274317

275318
" }}}

pylibs/ropevim.py

Lines changed: 79 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""ropevim, a vim mode for using rope refactoring library"""
2+
import glob
23
import os
34
import tempfile
45
import re
@@ -9,6 +10,9 @@
910

1011
import vim
1112

13+
# Gobal var to be able to shutup output
14+
_rope_quiet = False
15+
1216

1317
class VimUtils(environment.Environment):
1418

@@ -21,8 +25,8 @@ def ask(self, prompt, default=None, starting=None):
2125
if starting is None:
2226
starting = ''
2327
if default is not None:
24-
prompt = prompt + ('[%s] ' % default)
25-
result = call('input("%s", "%s")' % (prompt, starting))
28+
prompt = prompt + '[{0}] '.format(default)
29+
result = call('input("{0}", "{1}")'.format(prompt, starting))
2630
if default is not None and result == '':
2731
return default
2832
return result
@@ -32,11 +36,14 @@ def ask_values(self, prompt, values, default=None,
3236
if show_values or (show_values is None and len(values) < 14):
3337
self._print_values(values)
3438
if default is not None:
35-
prompt = prompt + ('[%s] ' % default)
39+
prompt = prompt + '[{0}] '.format(default)
3640
starting = starting or ''
3741
_completer.values = values
38-
answer = call('input("%s", "%s", "customlist,RopeValueCompleter")' %
39-
(prompt, starting))
42+
answer = call(
43+
'input("{0}", "{1}", "customlist,RopeValueCompleter")'.format(
44+
prompt, starting
45+
)
46+
)
4047
if answer is None:
4148
if 'cancel' in values:
4249
return 'cancel'
@@ -54,14 +61,14 @@ def _print_values(self, values):
5461
echo('\n'.join(numbered) + '\n')
5562

5663
def ask_directory(self, prompt, default=None, starting=None):
57-
return call('input("%s", ".", "dir")' % prompt)
64+
return call('input("{0}", ".", "dir")'.format(prompt))
5865

5966
def _update_proposals(self, values):
6067
self.completeopt = vim.eval('&completeopt')
6168
self.preview = 'preview' in self.completeopt
6269

6370
if not self.get('extended_complete'):
64-
return u','.join(u"'%s'" % self._completion_text(proposal)
71+
return u','.join(u"'{0}'".format(self._completion_text(proposal))
6572
for proposal in values)
6673

6774
return u','.join(self._extended_completion(proposal)
@@ -78,7 +85,7 @@ def ask_completion(self, prompt, values, starting=None):
7885
col = int(call('col(".")'))
7986
if starting:
8087
col -= len(starting)
81-
self._command(u'call complete(%s, [%s])' % (col, proposals),
88+
self._command(u'call complete({0}, [{1}])'.format(col, proposals),
8289
encode=True)
8390
return None
8491

@@ -95,8 +102,8 @@ def y_or_n(self, prompt):
95102
return self.yes_or_no(prompt)
96103

97104
def get(self, name, default=None):
98-
vimname = 'g:pymode_rope_%s' % name
99-
if str(vim.eval('exists("%s")' % vimname)) == '0':
105+
vimname = 'g:pymode_rope_{0}'.format(name)
106+
if str(vim.eval('exists("{0}")'.format(vimname))) == '0':
100107
return default
101108
result = vim.eval(vimname)
102109
if isinstance(result, str) and result.isdigit():
@@ -261,8 +268,9 @@ def _writedefs(self, locations, filename):
261268

262269
def show_doc(self, docs, altview=False):
263270
if docs:
264-
cmd = 'call pymode#ShowStr("%s")' % str(docs.replace('"', '\\"'))
265-
vim.command(cmd)
271+
vim.command(
272+
'call pymode#ShowStr("{0}")'.format(docs.replace('"', '\\"'))
273+
)
266274

267275
def preview_changes(self, diffs):
268276
echo(diffs)
@@ -281,23 +289,33 @@ def add_hook(self, name, callback, hook):
281289
'after_save': 'FileWritePost,BufWritePost',
282290
'exit': 'VimLeave'}
283291
self._add_function(name, callback)
284-
vim.command('autocmd %s *.py call %s()' %
285-
(mapping[hook], _vim_name(name)))
292+
vim.command(
293+
'autocmd {0} *.py call {1}()'.format(
294+
mapping[hook], _vim_name(name)
295+
)
296+
)
286297

287298
def _add_command(self, name, callback, key, prefix, prekey):
288299
self._add_function(name, callback, prefix)
289-
vim.command('command! -range %s call %s()' %
290-
(_vim_name(name), _vim_name(name)))
300+
vim.command(
301+
'command! -range {0} call {1}()'.format(
302+
_vim_name(name), _vim_name(name)
303+
)
304+
)
291305
if key is not None:
292306
key = prekey + key.replace(' ', '')
293-
vim.command('noremap %s :call %s()<cr>' % (key, _vim_name(name)))
307+
vim.command(
308+
'noremap {0} :call {1}()<cr>'.format(key, _vim_name(name))
309+
)
294310

295311
def _add_function(self, name, callback, prefix=False):
296312
globals()[name] = callback
297313
arg = 'None' if prefix else ''
298-
vim.command('function! %s()\n' % _vim_name(name) +
299-
'python ropevim.%s(%s)\n' % (name, arg) +
300-
'endfunction\n')
314+
vim.command(
315+
'function! {0}()\n'
316+
'python ropevim.{1}({2})\n'
317+
'endfunction\n'.format(_vim_name(name), name, arg)
318+
)
301319

302320
def _completion_data(self, proposal):
303321
return proposal
@@ -317,7 +335,7 @@ def _extended_completion(self, proposal):
317335

318336
if proposal.scope == 'parameter_keyword':
319337
default = proposal.get_default()
320-
ci["menu"] += '*' if default is None else '= %s' % default
338+
ci["menu"] += '*' if default is None else '= {0}'.format(default)
321339

322340
if self.preview and not ci['menu']:
323341
doc = proposal.get_doc()
@@ -328,9 +346,9 @@ def _extended_completion(self, proposal):
328346
def _conv(self, obj):
329347
if isinstance(obj, dict):
330348
return u'{' + u','.join([
331-
u"%s:%s" % (self._conv(key), self._conv(value))
349+
u"{0}:{1}".format(self._conv(key), self._conv(value))
332350
for key, value in obj.iteritems()]) + u'}'
333-
return u'"%s"' % str(obj).replace(u'"', u'\\"')
351+
return u'"{0}"'.format(str(obj).replace(u'"', u'\\"'))
334352

335353

336354
def _vim_name(name):
@@ -344,31 +362,38 @@ class VimProgress(object):
344362
def __init__(self, name):
345363
self.name = name
346364
self.last = 0
347-
status('%s ... ' % self.name)
365+
status('{0} ... '.format(self.name))
348366

349367
def update(self, percent):
350368
try:
351369
vim.eval('getchar(0)')
352370
except vim.error:
353-
raise KeyboardInterrupt('Task %s was interrupted!' % self.name)
371+
raise KeyboardInterrupt(
372+
'Task {0} was interrupted!'.format(self.name)
373+
)
354374
if percent > self.last + 4:
355-
status('%s ... %s%%%%' % (self.name, percent))
375+
status('{0} ... {1}%'.format(self.name, percent))
356376
self.last = percent
357377

358378
def done(self):
359-
status('%s ... done' % self.name)
379+
status('{0} ... done'.format(self.name))
360380

361381

362382
def echo(message):
383+
if _rope_quiet:
384+
return
363385
if isinstance(message, unicode):
364386
message = message.encode(vim.eval('&encoding'))
365387
print message
366388

367389

368390
def status(message):
391+
if _rope_quiet:
392+
return
393+
369394
if isinstance(message, unicode):
370395
message = message.encode(vim.eval('&encoding'))
371-
vim.command('redraw | echon "%s"' % message)
396+
vim.command('redraw | echon "{0}"'.format(message))
372397

373398

374399
def call(command):
@@ -395,13 +420,37 @@ def __call__(self, arg_lead, cmd_line, cursor_pos):
395420
else:
396421
result = [proposal for proposal in self.values
397422
if proposal.startswith(arg_lead)]
398-
vim.command('let s:completions = %s' % result)
423+
vim.command('let s:completions = {0}'.format(result))
424+
425+
426+
class RopeMode(interface.RopeMode):
427+
@decorators.global_command('o')
428+
def open_project(self, root=None, quiet=False):
429+
global _rope_quiet
430+
_rope_quiet = quiet
431+
432+
super(RopeMode, self).open_project(root=root)
433+
rope_project_dir = os.path.join(self.project.address, '.ropeproject')
434+
vimfiles = glob.glob(os.path.join(rope_project_dir, '*.vim'))
435+
436+
if not vimfiles:
437+
return
438+
439+
txt = 'Sourcing vim files under \'.ropeproject/\''
440+
progress = self.env.create_progress(txt)
441+
for idx, vimfile in enumerate(sorted(vimfiles)):
442+
progress.name = txt + ' ({0})'.format(os.path.basename(vimfile))
443+
vim.command(':silent source {0}'.format(vimfile))
444+
progress.update(idx * 100 / len(vimfiles))
399445

446+
progress.name = txt
447+
progress.done()
448+
echo('Project opened!')
400449

401450
decorators.logger.message = echo
402451
decorators.logger.only_short = True
403452

404453
_completer = _ValueCompleter()
405454

406455
_env = VimUtils()
407-
_interface = interface.RopeMode(env=_env)
456+
_interface = RopeMode(env=_env)

0 commit comments

Comments
 (0)