huge refactoring, moved new_buffer completely to python code

This commit is contained in:
David Halter
2013-08-23 23:38:52 +04:30
parent dcf884a6ca
commit b5b31aa0e6
2 changed files with 88 additions and 82 deletions

View File

@@ -95,25 +95,6 @@ endfunction
" ------------------------------------------------------------------------ " ------------------------------------------------------------------------
" helper functions " helper functions
" ------------------------------------------------------------------------ " ------------------------------------------------------------------------
function! jedi#new_buffer(path, options)
" options are what you can to edit the edit options
if g:jedi#use_tabs_not_buffers
Python jedi_vim.tabnew(jedi_vim.escape_file_path(vim.eval('a:path')), vim.eval('a:options'))
else
if !&hidden && &modified
w
endif
Python vim.command('edit ' + vim.eval('a:options') + jedi_vim.escape_file_path(vim.eval('a:path')))
endif
" sometimes syntax is being disabled and the filetype not set.
if !exists("g:syntax_on")
syntax enable
endif
if &filetype != 'python'
set filetype=python
endif
endfunction
function! jedi#add_goto_window() function! jedi#add_goto_window()
set lazyredraw set lazyredraw
@@ -134,7 +115,7 @@ function! s:goto_window_on_enter()
if l:data.bufnr if l:data.bufnr
" close goto_window buffer " close goto_window buffer
normal ZQ normal ZQ
call jedi#new_buffer(bufname(l:data.bufnr)) Python jedi_vim.new_buffer(vim.eval('bufname(l:data.bufnr)'))
call cursor(l:data.lnum, l:data.col) call cursor(l:data.lnum, l:data.col)
else else
echohl WarningMsg | echo "Builtin module cannot be opened." | echohl None echohl WarningMsg | echo "Builtin module cannot be opened." | echohl None

View File

@@ -14,6 +14,16 @@ import jedi.keywords
from jedi._compatibility import unicode from jedi._compatibility import unicode
def catch_and_print_exceptions(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
print(traceback.format_exc())
return None
return wrapper
def echo_highlight(msg): def echo_highlight(msg):
vim.command('echohl WarningMsg | echom "%s" | echohl None' % msg) vim.command('echohl WarningMsg | echom "%s" | echohl None' % msg)
@@ -38,6 +48,7 @@ class PythonToVimStr(unicode):
return '"%s"' % s.replace('\\', '\\\\').replace('"', r'\"') return '"%s"' % s.replace('\\', '\\\\').replace('"', r'\"')
@catch_and_print_exceptions
def get_script(source=None, column=None): def get_script(source=None, column=None):
jedi.settings.additional_dynamic_modules = [b.name for b in vim.buffers jedi.settings.additional_dynamic_modules = [b.name for b in vim.buffers
if b.name is not None and b.name.endswith('.py')] if b.name is not None and b.name.endswith('.py')]
@@ -51,6 +62,7 @@ def get_script(source=None, column=None):
return jedi.Script(source, row, column, buf_path, encoding) return jedi.Script(source, row, column, buf_path, encoding)
@catch_and_print_exceptions
def completions(): def completions():
row, column = vim.current.window.cursor row, column = vim.current.window.cursor
clear_call_signatures() clear_call_signatures()
@@ -102,6 +114,7 @@ def completions():
vim.command('return ' + strout) vim.command('return ' + strout)
@catch_and_print_exceptions
def goto(is_definition=False, is_related_name=False, no_output=False): def goto(is_definition=False, is_related_name=False, no_output=False):
definitions = [] definitions = []
script = get_script() script = get_script()
@@ -114,10 +127,6 @@ def goto(is_definition=False, is_related_name=False, no_output=False):
definitions = script.goto_assignments() definitions = script.goto_assignments()
except jedi.NotFoundError: except jedi.NotFoundError:
echo_highlight( "Cannot follow nothing. Put your cursor on a valid name.") echo_highlight( "Cannot follow nothing. Put your cursor on a valid name.")
except Exception:
# print to stdout, will be in :messages
echo_highlight("Some different eror, this shouldn't happen.")
print(traceback.format_exc())
else: else:
if no_output: if no_output:
return definitions return definitions
@@ -158,6 +167,7 @@ def goto(is_definition=False, is_related_name=False, no_output=False):
return definitions return definitions
@catch_and_print_exceptions
def show_documentation(): def show_documentation():
script = get_script() script = get_script()
try: try:
@@ -180,6 +190,7 @@ def show_documentation():
vim.command('let l:doc_lines = %s' % len(text.split('\n'))) vim.command('let l:doc_lines = %s' % len(text.split('\n')))
@catch_and_print_exceptions
def clear_call_signatures(): def clear_call_signatures():
cursor = vim.current.window.cursor cursor = vim.current.window.cursor
e = vim.eval('g:jedi#call_signature_escape') e = vim.eval('g:jedi#call_signature_escape')
@@ -196,75 +207,74 @@ def clear_call_signatures():
vim.current.window.cursor = cursor vim.current.window.cursor = cursor
@catch_and_print_exceptions
def show_call_signatures(signatures=()): def show_call_signatures(signatures=()):
if vim.eval("has('conceal') && g:jedi#show_call_signatures") == '0': if vim.eval("has('conceal') && g:jedi#show_call_signatures") == '0':
return return
try: if signatures == ():
if signatures == (): signatures = get_script().call_signatures()
signatures = get_script().call_signatures() clear_call_signatures()
clear_call_signatures()
if not signatures: if not signatures:
return return
for i, signature in enumerate(signatures): for i, signature in enumerate(signatures):
line, column = signature.bracket_start line, column = signature.bracket_start
# signatures are listed above each other # signatures are listed above each other
line_to_replace = line - i - 1 line_to_replace = line - i - 1
# because there's a space before the bracket # because there's a space before the bracket
insert_column = column - 1 insert_column = column - 1
if insert_column < 0 or line_to_replace <= 0: if insert_column < 0 or line_to_replace <= 0:
# Edge cases, when the call signature has no space on the screen. # Edge cases, when the call signature has no space on the screen.
break break
# TODO check if completion menu is above or below # TODO check if completion menu is above or below
line = vim.eval("getline(%s)" % line_to_replace) line = vim.eval("getline(%s)" % line_to_replace)
params = [p.get_code().replace('\n', '') for p in signature.params] params = [p.get_code().replace('\n', '') for p in signature.params]
try: try:
params[signature.index] = '*%s*' % params[signature.index] params[signature.index] = '*%s*' % params[signature.index]
except (IndexError, TypeError): except (IndexError, TypeError):
pass pass
# This stuff is reaaaaally a hack! I cannot stress enough, that # This stuff is reaaaaally a hack! I cannot stress enough, that
# this is a stupid solution. But there is really no other yet. # this is a stupid solution. But there is really no other yet.
# There is no possibility in VIM to draw on the screen, but there # There is no possibility in VIM to draw on the screen, but there
# will be one (see :help todo Patch to access screen under Python. # will be one (see :help todo Patch to access screen under Python.
# (Marko Mahni, 2010 Jul 18)) # (Marko Mahni, 2010 Jul 18))
text = " (%s) " % ', '.join(params) text = " (%s) " % ', '.join(params)
text = ' ' * (insert_column - len(line)) + text text = ' ' * (insert_column - len(line)) + text
end_column = insert_column + len(text) - 2 # -2 due to bold symbols end_column = insert_column + len(text) - 2 # -2 due to bold symbols
# Need to decode it with utf8, because vim returns always a python 2 # Need to decode it with utf8, because vim returns always a python 2
# string even if it is unicode. # string even if it is unicode.
e = vim.eval('g:jedi#call_signature_escape') e = vim.eval('g:jedi#call_signature_escape')
if hasattr(e, 'decode'): if hasattr(e, 'decode'):
e = e.decode('UTF-8') e = e.decode('UTF-8')
# replace line before with cursor # replace line before with cursor
regex = "xjedi=%sx%sxjedix".replace('x', e) regex = "xjedi=%sx%sxjedix".replace('x', e)
prefix, replace = line[:insert_column], line[insert_column:end_column] prefix, replace = line[:insert_column], line[insert_column:end_column]
# Check the replace stuff for strings, to append them # Check the replace stuff for strings, to append them
# (don't want to break the syntax) # (don't want to break the syntax)
regex_quotes = r'''\\*["']+''' regex_quotes = r'''\\*["']+'''
# `add` are all the quotation marks. # `add` are all the quotation marks.
# join them with a space to avoid producing ''' # join them with a space to avoid producing '''
add = ' '.join(re.findall(regex_quotes, replace)) add = ' '.join(re.findall(regex_quotes, replace))
# search backwards # search backwards
if add and replace[0] in ['"', "'"]: if add and replace[0] in ['"', "'"]:
a = re.search(regex_quotes + '$', prefix) a = re.search(regex_quotes + '$', prefix)
add = ('' if a is None else a.group(0)) + add add = ('' if a is None else a.group(0)) + add
tup = '%s, %s' % (len(add), replace) tup = '%s, %s' % (len(add), replace)
repl = prefix + (regex % (tup, text)) + add + line[end_column:] repl = prefix + (regex % (tup, text)) + add + line[end_column:]
vim.eval('setline(%s, %s)' % (line_to_replace, repr(PythonToVimStr(repl)))) vim.eval('setline(%s, %s)' % (line_to_replace, repr(PythonToVimStr(repl))))
except Exception:
print(traceback.format_exc())
@catch_and_print_exceptions
def rename(): def rename():
if not int(vim.eval('a:0')): if not int(vim.eval('a:0')):
_rename_cursor = vim.current.window.cursor _rename_cursor = vim.current.window.cursor
@@ -312,6 +322,7 @@ def rename():
echo_highlight('Jedi did %s renames!' % len(temp_rename)) echo_highlight('Jedi did %s renames!' % len(temp_rename))
@catch_and_print_exceptions
def py_import(): def py_import():
# args are the same as for the :edit command # args are the same as for the :edit command
args = shsplit(vim.eval('a:args')) args = shsplit(vim.eval('a:args'))
@@ -330,6 +341,7 @@ def py_import():
new_buffer(completion.module_path, cmd_args) new_buffer(completion.module_path, cmd_args)
@catch_and_print_exceptions
def py_import_completions(): def py_import_completions():
argl = vim.eval('a:argl') argl = vim.eval('a:argl')
try: try:
@@ -344,12 +356,25 @@ def py_import_completions():
vim.command("return '%s'" % '\n'.join(comps)) vim.command("return '%s'" % '\n'.join(comps))
@catch_and_print_exceptions
def new_buffer(path, options=''): def new_buffer(path, options=''):
path = repr(PythonToVimStr(path)) # options are what you can to edit the edit options
vim.eval("jedi#new_buffer(%s, '%s')" % (path, options)) if vim.eval('g:jedi#use_tabs_not_buffers') == '1':
_tabnew(path, options)
else:
if vim.eval("!&hidden && &modified && bufname('%') != ") == '1':
vim.command('w')
print 'x'
vim.command('edit %s %s' (options, escape_file_path(path)))
# sometimes syntax is being disabled and the filetype not set.
if vim.eval('!exists("g:syntax_on")') == '1':
vim.command('syntax enable')
if vim.eval("&filetype != 'python'") == '1':
vim.command('set filetype=python')
def tabnew(path, options=''): @catch_and_print_exceptions
def _tabnew(path, options=''):
""" """
Open a file in a new tab or switch to an existing one. Open a file in a new tab or switch to an existing one.
@@ -357,7 +382,7 @@ def tabnew(path, options=''):
""" """
path = os.path.abspath(path) path = os.path.abspath(path)
if vim.eval('has("gui")') == '1': if vim.eval('has("gui")') == '1':
vim.command('tab drop %s %s' % (options, path)) vim.command('tab drop %s %s' % (options, escape_file_path(path)))
return return
for tab_nr in range(int(vim.eval("tabpagenr('$')"))): for tab_nr in range(int(vim.eval("tabpagenr('$')"))):
@@ -379,7 +404,7 @@ def tabnew(path, options=''):
break break
else: else:
# tab doesn't exist, add a new one. # tab doesn't exist, add a new one.
vim.command('tabnew %s' % path) vim.command('tabnew %s' % escape_file_path(path))
def escape_file_path(path): def escape_file_path(path):