| 1 |
|
| 2 |
""" |
| 3 |
The Python parts of the Jedi library for VIM. It is mostly about communicating |
| 4 |
with VIM. |
| 5 |
""" |
| 6 |
|
| 7 |
from typing import Optional |
| 8 |
import traceback |
| 9 |
import re |
| 10 |
import os |
| 11 |
import sys |
| 12 |
from shlex import split as shsplit |
| 13 |
from contextlib import contextmanager |
| 14 |
from pathlib import Path |
| 15 |
try: |
| 16 |
from itertools import zip_longest |
| 17 |
except ImportError: |
| 18 |
from itertools import izip_longest as zip_longest |
| 19 |
|
| 20 |
import vim |
| 21 |
|
| 22 |
is_py3 = sys.version_info[0] >= 3 |
| 23 |
if is_py3: |
| 24 |
ELLIPSIS = "…" |
| 25 |
unicode = str |
| 26 |
else: |
| 27 |
ELLIPSIS = u"…" |
| 28 |
|
| 29 |
|
| 30 |
try: |
| 31 |
|
| 32 |
|
| 33 |
sys.prefix = sys.base_prefix |
| 34 |
sys.exec_prefix = sys.base_exec_prefix |
| 35 |
except AttributeError: |
| 36 |
|
| 37 |
pass |
| 38 |
|
| 39 |
|
| 40 |
class PythonToVimStr(unicode): |
| 41 |
""" Vim has a different string implementation of single quotes """ |
| 42 |
__slots__ = [] |
| 43 |
|
| 44 |
def __new__(cls, obj, encoding='UTF-8'): |
| 45 |
if not (is_py3 or isinstance(obj, unicode)): |
| 46 |
obj = unicode.__new__(cls, obj, encoding) |
| 47 |
|
| 48 |
|
| 49 |
obj = obj.replace('\0', '\\0') |
| 50 |
return unicode.__new__(cls, obj) |
| 51 |
|
| 52 |
def __repr__(self): |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
if unicode is str: |
| 58 |
s = self |
| 59 |
else: |
| 60 |
s = self.encode('UTF-8') |
| 61 |
return '"%s"' % s.replace('\\', '\\\\').replace('"', r'\"') |
| 62 |
|
| 63 |
|
| 64 |
class VimError(Exception): |
| 65 |
def __init__(self, message, throwpoint, executing): |
| 66 |
super(type(self), self).__init__(message) |
| 67 |
self.message = message |
| 68 |
self.throwpoint = throwpoint |
| 69 |
self.executing = executing |
| 70 |
|
| 71 |
def __str__(self): |
| 72 |
return "{}; created by {!r} (in {})".format( |
| 73 |
self.message, self.executing, self.throwpoint |
| 74 |
) |
| 75 |
|
| 76 |
|
| 77 |
def _catch_exception(string, is_eval): |
| 78 |
""" |
| 79 |
Interface between vim and python calls back to it. |
| 80 |
Necessary, because the exact error message is not given by `vim.error`. |
| 81 |
""" |
| 82 |
result = vim.eval('jedi#_vim_exceptions({0}, {1})'.format( |
| 83 |
repr(PythonToVimStr(string, 'UTF-8')), int(is_eval))) |
| 84 |
if 'exception' in result: |
| 85 |
raise VimError(result['exception'], result['throwpoint'], string) |
| 86 |
return result['result'] |
| 87 |
|
| 88 |
|
| 89 |
def vim_command(string): |
| 90 |
_catch_exception(string, is_eval=False) |
| 91 |
|
| 92 |
|
| 93 |
def vim_eval(string): |
| 94 |
return _catch_exception(string, is_eval=True) |
| 95 |
|
| 96 |
|
| 97 |
def no_jedi_warning(error=None): |
| 98 |
vim.command('echohl WarningMsg') |
| 99 |
vim.command('echom "Please install Jedi if you want to use jedi-vim."') |
| 100 |
if error: |
| 101 |
vim.command('echom "The error was: {0}"'.format(error)) |
| 102 |
vim.command('echohl None') |
| 103 |
|
| 104 |
|
| 105 |
def echo_highlight(msg): |
| 106 |
vim_command('echohl WarningMsg | echom "jedi-vim: {0}" | echohl None'.format( |
| 107 |
str(msg).replace('"', '\\"'))) |
| 108 |
|
| 109 |
|
| 110 |
jedi_path = os.path.join(os.path.dirname(__file__), 'jedi') |
| 111 |
sys.path.insert(0, jedi_path) |
| 112 |
parso_path = os.path.join(os.path.dirname(__file__), 'parso') |
| 113 |
sys.path.insert(0, parso_path) |
| 114 |
|
| 115 |
try: |
| 116 |
import jedi |
| 117 |
except ImportError: |
| 118 |
jedi = None |
| 119 |
jedi_import_error = sys.exc_info() |
| 120 |
else: |
| 121 |
try: |
| 122 |
version = jedi.__version__ |
| 123 |
except Exception as e: |
| 124 |
echo_highlight( |
| 125 |
"Error when loading the jedi python module ({0}). " |
| 126 |
"Please ensure that Jedi is installed correctly (see Installation " |
| 127 |
"in the README.".format(e)) |
| 128 |
jedi = None |
| 129 |
else: |
| 130 |
if isinstance(version, str): |
| 131 |
|
| 132 |
from jedi import utils |
| 133 |
version = utils.version_info() |
| 134 |
if version < (0, 7): |
| 135 |
echo_highlight('Please update your Jedi version, it is too old.') |
| 136 |
finally: |
| 137 |
sys.path.remove(jedi_path) |
| 138 |
sys.path.remove(parso_path) |
| 139 |
|
| 140 |
|
| 141 |
class VimCompat: |
| 142 |
_eval_cache = {} |
| 143 |
_func_cache = {} |
| 144 |
|
| 145 |
@classmethod |
| 146 |
def has(cls, what): |
| 147 |
try: |
| 148 |
return cls._eval_cache[what] |
| 149 |
except KeyError: |
| 150 |
ret = cls._eval_cache[what] = cls.call('has', what) |
| 151 |
return ret |
| 152 |
|
| 153 |
@classmethod |
| 154 |
def call(cls, func, *args): |
| 155 |
try: |
| 156 |
f = cls._func_cache[func] |
| 157 |
except KeyError: |
| 158 |
if IS_NVIM: |
| 159 |
f = cls._func_cache[func] = getattr(vim.funcs, func) |
| 160 |
else: |
| 161 |
f = cls._func_cache[func] = vim.Function(func) |
| 162 |
return f(*args) |
| 163 |
|
| 164 |
@classmethod |
| 165 |
def setqflist(cls, items, title, context): |
| 166 |
if cls.has('patch-7.4.2200'): |
| 167 |
what = {'title': title} |
| 168 |
if cls.has('patch-8.0.0590'): |
| 169 |
what['context'] = {'jedi_usages': context} |
| 170 |
if cls.has('patch-8.0.0657'): |
| 171 |
what['items'] = items |
| 172 |
cls.call('setqflist', [], ' ', what) |
| 173 |
else: |
| 174 |
|
| 175 |
cls.call('setqflist', items) |
| 176 |
cls.call('setqflist', items, 'a', what) |
| 177 |
else: |
| 178 |
cls.call('setqflist', items) |
| 179 |
|
| 180 |
@classmethod |
| 181 |
def setqflist_title(cls, title): |
| 182 |
if cls.has('patch-7.4.2200'): |
| 183 |
cls.call('setqflist', [], 'a', {'title': title}) |
| 184 |
|
| 185 |
@classmethod |
| 186 |
def can_update_current_qflist_for_context(cls, context): |
| 187 |
if cls.has('patch-8.0.0590'): |
| 188 |
return cls.call('getqflist', {'context': 1})['context'] == { |
| 189 |
'jedi_usages': context, |
| 190 |
} |
| 191 |
|
| 192 |
|
| 193 |
def catch_and_print_exceptions(func): |
| 194 |
def wrapper(*args, **kwargs): |
| 195 |
try: |
| 196 |
return func(*args, **kwargs) |
| 197 |
except (Exception, vim.error): |
| 198 |
print(traceback.format_exc()) |
| 199 |
return None |
| 200 |
return wrapper |
| 201 |
|
| 202 |
|
| 203 |
def _check_jedi_availability(show_error=False): |
| 204 |
def func_receiver(func): |
| 205 |
def wrapper(*args, **kwargs): |
| 206 |
if jedi is None: |
| 207 |
if show_error: |
| 208 |
no_jedi_warning() |
| 209 |
return |
| 210 |
else: |
| 211 |
return func(*args, **kwargs) |
| 212 |
return wrapper |
| 213 |
return func_receiver |
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
_current_project_cache = None, None |
| 218 |
|
| 219 |
|
| 220 |
def get_project(): |
| 221 |
vim_environment_path = vim_eval( |
| 222 |
"get(b:, 'jedi_environment_path', g:jedi#environment_path)" |
| 223 |
) |
| 224 |
vim_project_path = vim_eval("g:jedi#project_path") |
| 225 |
|
| 226 |
vim_added_sys_path = vim_eval("get(g:, 'jedi#added_sys_path', [])") |
| 227 |
vim_added_sys_path += vim_eval("get(b:, 'jedi_added_sys_path', [])") |
| 228 |
|
| 229 |
global _current_project_cache |
| 230 |
cache_key = dict(project_path=vim_project_path, |
| 231 |
environment_path=vim_environment_path, |
| 232 |
added_sys_path=vim_added_sys_path) |
| 233 |
if cache_key == _current_project_cache[0]: |
| 234 |
return _current_project_cache[1] |
| 235 |
|
| 236 |
if vim_environment_path in ("auto", "", None): |
| 237 |
environment_path = None |
| 238 |
else: |
| 239 |
environment_path = vim_environment_path |
| 240 |
|
| 241 |
if vim_project_path in ("auto", "", None): |
| 242 |
project_path = jedi.get_default_project().path |
| 243 |
else: |
| 244 |
project_path = vim_project_path |
| 245 |
|
| 246 |
project = jedi.Project(project_path, |
| 247 |
environment_path=environment_path, |
| 248 |
added_sys_path=vim_added_sys_path) |
| 249 |
|
| 250 |
_current_project_cache = cache_key, project |
| 251 |
return project |
| 252 |
|
| 253 |
|
| 254 |
@catch_and_print_exceptions |
| 255 |
def choose_environment(): |
| 256 |
args = shsplit(vim.eval('a:args')) |
| 257 |
|
| 258 |
envs = list(jedi.find_system_environments()) |
| 259 |
envs.extend(jedi.find_virtualenvs(paths=args or None)) |
| 260 |
|
| 261 |
env_paths = [env.executable for env in envs] |
| 262 |
|
| 263 |
vim_command('belowright new') |
| 264 |
vim.current.buffer[:] = env_paths |
| 265 |
vim.current.buffer.name = "Hit Enter to Choose an Environment" |
| 266 |
vim_command( |
| 267 |
'setlocal buftype=nofile bufhidden=wipe noswapfile nobuflisted readonly nomodifiable') |
| 268 |
vim_command('noremap <buffer> <ESC> :bw<CR>') |
| 269 |
vim_command('noremap <buffer> <CR> :python3 jedi_vim.choose_environment_hit_enter()<CR>') |
| 270 |
|
| 271 |
|
| 272 |
@catch_and_print_exceptions |
| 273 |
def choose_environment_hit_enter(): |
| 274 |
vim.vars['jedi#environment_path'] = vim.current.line |
| 275 |
vim_command('bd') |
| 276 |
|
| 277 |
|
| 278 |
@catch_and_print_exceptions |
| 279 |
def load_project(): |
| 280 |
path = vim.eval('a:args') |
| 281 |
vim.vars['jedi#project_path'] = path |
| 282 |
env_path = vim_eval("g:jedi#environment_path") |
| 283 |
if env_path == 'auto': |
| 284 |
env_path = None |
| 285 |
if path: |
| 286 |
try: |
| 287 |
project = jedi.Project.load(path) |
| 288 |
except FileNotFoundError: |
| 289 |
project = jedi.Project(path, environment_path=env_path) |
| 290 |
project.save() |
| 291 |
else: |
| 292 |
project = jedi.get_default_project() |
| 293 |
path = project.path |
| 294 |
project.save() |
| 295 |
|
| 296 |
global _current_project_cache |
| 297 |
cache_key = dict(project_path=path, |
| 298 |
environment_path=env_path, |
| 299 |
added_sys_path=[]) |
| 300 |
_current_project_cache = cache_key, project |
| 301 |
|
| 302 |
|
| 303 |
@catch_and_print_exceptions |
| 304 |
def get_script(source=None): |
| 305 |
jedi.settings.additional_dynamic_modules = [ |
| 306 |
b.name for b in vim.buffers if ( |
| 307 |
b.name is not None and |
| 308 |
b.name.endswith('.py') and |
| 309 |
b.options['buflisted'])] |
| 310 |
if source is None: |
| 311 |
source = '\n'.join(vim.current.buffer) |
| 312 |
buf_path = vim.current.buffer.name |
| 313 |
if not buf_path: |
| 314 |
|
| 315 |
buf_path = None |
| 316 |
|
| 317 |
return jedi.Script(source, path=buf_path, project=get_project()) |
| 318 |
|
| 319 |
|
| 320 |
def get_pos(column=None): |
| 321 |
row = vim.current.window.cursor[0] |
| 322 |
if column is None: |
| 323 |
column = vim.current.window.cursor[1] |
| 324 |
return row, column |
| 325 |
|
| 326 |
|
| 327 |
@_check_jedi_availability(show_error=False) |
| 328 |
@catch_and_print_exceptions |
| 329 |
def completions(): |
| 330 |
jedi.settings.case_insensitive_completion = \ |
| 331 |
bool(int(vim_eval("get(b:, 'jedi_case_insensitive_completion', " |
| 332 |
"g:jedi#case_insensitive_completion)"))) |
| 333 |
|
| 334 |
row, column = vim.current.window.cursor |
| 335 |
|
| 336 |
|
| 337 |
if int(vim_eval("g:jedi#show_call_signatures")) == 1: |
| 338 |
clear_call_signatures() |
| 339 |
if vim.eval('a:findstart') == '1': |
| 340 |
count = 0 |
| 341 |
for char in reversed(vim.current.line[:column]): |
| 342 |
if not re.match(r'[\w\d]', char): |
| 343 |
break |
| 344 |
count += 1 |
| 345 |
vim.command('return %i' % (column - count)) |
| 346 |
else: |
| 347 |
base = vim.eval('a:base') |
| 348 |
source = '' |
| 349 |
for i, line in enumerate(vim.current.buffer): |
| 350 |
|
| 351 |
if i == row - 1: |
| 352 |
source += line[:column] + base + line[column:] |
| 353 |
else: |
| 354 |
source += line |
| 355 |
source += '\n' |
| 356 |
|
| 357 |
column += len(base) |
| 358 |
try: |
| 359 |
script = get_script(source=source) |
| 360 |
completions = script.complete(*get_pos(column)) |
| 361 |
signatures = script.get_signatures(*get_pos(column)) |
| 362 |
|
| 363 |
add_info = \ |
| 364 |
any(option in vim.eval("&completeopt").split(",") |
| 365 |
for option in ("preview", "popup")) |
| 366 |
out = [] |
| 367 |
for c in completions: |
| 368 |
d = dict(word=PythonToVimStr(c.name[:len(base)] + c.complete), |
| 369 |
abbr=PythonToVimStr(c.name_with_symbols), |
| 370 |
|
| 371 |
menu=PythonToVimStr(c.description), |
| 372 |
icase=1, |
| 373 |
dup=1 |
| 374 |
) |
| 375 |
if add_info: |
| 376 |
try: |
| 377 |
d["info"] = PythonToVimStr(c.docstring()) |
| 378 |
except Exception: |
| 379 |
print("jedi-vim: error with docstring for %r: %s" % ( |
| 380 |
c, traceback.format_exc())) |
| 381 |
out.append(d) |
| 382 |
|
| 383 |
strout = str(out) |
| 384 |
except Exception: |
| 385 |
|
| 386 |
print(traceback.format_exc()) |
| 387 |
strout = '' |
| 388 |
completions = [] |
| 389 |
signatures = [] |
| 390 |
|
| 391 |
show_call_signatures(signatures) |
| 392 |
vim.command('return ' + strout) |
| 393 |
|
| 394 |
|
| 395 |
@contextmanager |
| 396 |
def tempfile(content): |
| 397 |
|
| 398 |
|
| 399 |
with open(vim_eval('tempname()'), 'w') as f: |
| 400 |
f.write(content) |
| 401 |
try: |
| 402 |
yield f |
| 403 |
finally: |
| 404 |
os.unlink(f.name) |
| 405 |
|
| 406 |
|
| 407 |
@_check_jedi_availability(show_error=True) |
| 408 |
@catch_and_print_exceptions |
| 409 |
def goto(mode="goto"): |
| 410 |
""" |
| 411 |
:param str mode: "definition", "assignment", "goto" |
| 412 |
:rtype: list of jedi.api.classes.Name |
| 413 |
""" |
| 414 |
script = get_script() |
| 415 |
pos = get_pos() |
| 416 |
if mode == "goto": |
| 417 |
names = script.goto(*pos, follow_imports=True) |
| 418 |
elif mode == "definition": |
| 419 |
names = script.infer(*pos) |
| 420 |
elif mode == "assignment": |
| 421 |
names = script.goto(*pos) |
| 422 |
elif mode == "stubs": |
| 423 |
names = script.goto(*pos, follow_imports=True, only_stubs=True) |
| 424 |
|
| 425 |
if not names: |
| 426 |
echo_highlight("Couldn't find any definitions for this.") |
| 427 |
elif len(names) == 1 and mode != "related_name": |
| 428 |
n = list(names)[0] |
| 429 |
_goto_specific_name(n) |
| 430 |
else: |
| 431 |
show_goto_multi_results(names, mode) |
| 432 |
return names |
| 433 |
|
| 434 |
|
| 435 |
def _goto_specific_name(n, options=''): |
| 436 |
if n.column is None: |
| 437 |
if n.is_keyword: |
| 438 |
echo_highlight("Cannot get the definition of Python keywords.") |
| 439 |
else: |
| 440 |
name = 'Namespaces' if n.type == 'namespace' else 'Builtin modules' |
| 441 |
echo_highlight( |
| 442 |
"%s cannot be displayed (%s)." |
| 443 |
% (name, n.full_name or n.name) |
| 444 |
) |
| 445 |
else: |
| 446 |
using_tagstack = int(vim_eval('g:jedi#use_tag_stack')) == 1 |
| 447 |
result = set_buffer(n.module_path, options=options, |
| 448 |
using_tagstack=using_tagstack) |
| 449 |
if not result: |
| 450 |
return [] |
| 451 |
if (using_tagstack and n.module_path and |
| 452 |
n.module_path.exists()): |
| 453 |
tagname = n.name |
| 454 |
with tempfile('{0}\t{1}\t{2}'.format( |
| 455 |
tagname, n.module_path, 'call cursor({0}, {1})'.format( |
| 456 |
n.line, n.column + 1))) as f: |
| 457 |
old_tags = vim.eval('&tags') |
| 458 |
old_wildignore = vim.eval('&wildignore') |
| 459 |
try: |
| 460 |
|
| 461 |
vim.command('set wildignore=') |
| 462 |
vim.command('let &tags = %s' % |
| 463 |
repr(PythonToVimStr(f.name))) |
| 464 |
vim.command('tjump %s' % tagname) |
| 465 |
finally: |
| 466 |
vim.command('let &tags = %s' % |
| 467 |
repr(PythonToVimStr(old_tags))) |
| 468 |
vim.command('let &wildignore = %s' % |
| 469 |
repr(PythonToVimStr(old_wildignore))) |
| 470 |
vim.current.window.cursor = n.line, n.column |
| 471 |
|
| 472 |
|
| 473 |
def relpath(path): |
| 474 |
"""Make path relative to cwd if it is below.""" |
| 475 |
abspath = os.path.abspath(path) |
| 476 |
if abspath.startswith(os.getcwd()): |
| 477 |
return os.path.relpath(path) |
| 478 |
return path |
| 479 |
|
| 480 |
|
| 481 |
def annotate_description(n): |
| 482 |
code = n.get_line_code().strip() |
| 483 |
if n.type == 'statement': |
| 484 |
return code |
| 485 |
if n.type == 'function': |
| 486 |
if code.startswith('def'): |
| 487 |
return code |
| 488 |
typ = 'def' |
| 489 |
else: |
| 490 |
typ = n.type |
| 491 |
return '[%s] %s' % (typ, code) |
| 492 |
|
| 493 |
|
| 494 |
def show_goto_multi_results(names, mode): |
| 495 |
"""Create (or reuse) a quickfix list for multiple names.""" |
| 496 |
global _current_names |
| 497 |
|
| 498 |
lst = [] |
| 499 |
(row, col) = vim.current.window.cursor |
| 500 |
current_idx = None |
| 501 |
current_def = None |
| 502 |
for n in names: |
| 503 |
if n.column is None: |
| 504 |
|
| 505 |
|
| 506 |
lst.append(dict(text=PythonToVimStr(n.description))) |
| 507 |
else: |
| 508 |
text = annotate_description(n) |
| 509 |
lst.append(dict(filename=PythonToVimStr(relpath(str(n.module_path))), |
| 510 |
lnum=n.line, col=n.column + 1, |
| 511 |
text=PythonToVimStr(text))) |
| 512 |
|
| 513 |
|
| 514 |
if n.line == row and n.column <= col: |
| 515 |
if (current_idx is None |
| 516 |
or (abs(lst[current_idx]["col"] - col) |
| 517 |
> abs(n.column - col))): |
| 518 |
current_idx = len(lst) |
| 519 |
current_def = n |
| 520 |
|
| 521 |
|
| 522 |
qf_title = mode |
| 523 |
if current_def is not None: |
| 524 |
if current_def.full_name: |
| 525 |
qf_title += ": " + current_def.full_name |
| 526 |
else: |
| 527 |
qf_title += ": " + str(current_def) |
| 528 |
select_entry = current_idx |
| 529 |
else: |
| 530 |
select_entry = 0 |
| 531 |
|
| 532 |
qf_context = id(names) |
| 533 |
if (_current_names |
| 534 |
and VimCompat.can_update_current_qflist_for_context(qf_context)): |
| 535 |
|
| 536 |
VimCompat.setqflist_title(qf_title) |
| 537 |
vim_command('%dcc' % select_entry) |
| 538 |
else: |
| 539 |
VimCompat.setqflist(lst, title=qf_title, context=qf_context) |
| 540 |
for_usages = mode == "usages" |
| 541 |
vim_eval('jedi#add_goto_window(%d, %d)' % (for_usages, len(lst))) |
| 542 |
vim_command('%d' % select_entry) |
| 543 |
|
| 544 |
|
| 545 |
def _same_names(a, b): |
| 546 |
"""Compare without _inference_state. |
| 547 |
|
| 548 |
Ref: https://github.com/davidhalter/jedi-vim/issues/952) |
| 549 |
""" |
| 550 |
return all( |
| 551 |
x._name.start_pos == y._name.start_pos |
| 552 |
and x.module_path == y.module_path |
| 553 |
and x.name == y.name |
| 554 |
for x, y in zip(a, b) |
| 555 |
) |
| 556 |
|
| 557 |
|
| 558 |
@catch_and_print_exceptions |
| 559 |
def usages(visuals=True): |
| 560 |
script = get_script() |
| 561 |
names = script.get_references(*get_pos()) |
| 562 |
if not names: |
| 563 |
echo_highlight("No usages found here.") |
| 564 |
return names |
| 565 |
|
| 566 |
if visuals: |
| 567 |
global _current_names |
| 568 |
|
| 569 |
if _current_names: |
| 570 |
if _same_names(_current_names, names): |
| 571 |
names = _current_names |
| 572 |
else: |
| 573 |
clear_usages() |
| 574 |
assert not _current_names |
| 575 |
|
| 576 |
show_goto_multi_results(names, "usages") |
| 577 |
if not _current_names: |
| 578 |
_current_names = names |
| 579 |
highlight_usages() |
| 580 |
else: |
| 581 |
assert names is _current_names |
| 582 |
return names |
| 583 |
|
| 584 |
|
| 585 |
_current_names = None |
| 586 |
"""Current definitions to use for highlighting.""" |
| 587 |
_pending_names = {} |
| 588 |
"""Pending definitions for unloaded buffers.""" |
| 589 |
_placed_names_in_buffers = set() |
| 590 |
"""Set of buffers for faster cleanup.""" |
| 591 |
|
| 592 |
|
| 593 |
IS_NVIM = hasattr(vim, 'from_nvim') |
| 594 |
if IS_NVIM: |
| 595 |
vim_prop_add = None |
| 596 |
else: |
| 597 |
vim_prop_type_added = False |
| 598 |
try: |
| 599 |
vim_prop_add = vim.Function("prop_add") |
| 600 |
except ValueError: |
| 601 |
vim_prop_add = None |
| 602 |
else: |
| 603 |
vim_prop_remove = vim.Function("prop_remove") |
| 604 |
|
| 605 |
|
| 606 |
def clear_usages(): |
| 607 |
"""Clear existing highlights.""" |
| 608 |
global _current_names |
| 609 |
if _current_names is None: |
| 610 |
return |
| 611 |
_current_names = None |
| 612 |
|
| 613 |
if IS_NVIM: |
| 614 |
for buf in _placed_names_in_buffers: |
| 615 |
src_ids = buf.vars.get('_jedi_usages_src_ids') |
| 616 |
if src_ids is not None: |
| 617 |
for src_id in src_ids: |
| 618 |
buf.clear_highlight(src_id) |
| 619 |
elif vim_prop_add: |
| 620 |
for buf in _placed_names_in_buffers: |
| 621 |
vim_prop_remove({ |
| 622 |
'type': 'jediUsage', |
| 623 |
'all': 1, |
| 624 |
'bufnr': buf.number, |
| 625 |
}) |
| 626 |
else: |
| 627 |
|
| 628 |
assert _current_names is None |
| 629 |
highlight_usages_for_vim_win() |
| 630 |
|
| 631 |
_placed_names_in_buffers.clear() |
| 632 |
|
| 633 |
|
| 634 |
def highlight_usages(): |
| 635 |
"""Set usage names to be highlighted. |
| 636 |
|
| 637 |
With Neovim it will use the nvim_buf_add_highlight API to highlight all |
| 638 |
buffers already. |
| 639 |
|
| 640 |
With Vim without support for text-properties only the current window is |
| 641 |
highlighted via matchaddpos, and autocommands are setup to highlight other |
| 642 |
windows on demand. Otherwise Vim's text-properties are used. |
| 643 |
""" |
| 644 |
global _current_names, _pending_names |
| 645 |
|
| 646 |
names = _current_names |
| 647 |
_pending_names = {} |
| 648 |
|
| 649 |
if IS_NVIM or vim_prop_add: |
| 650 |
bufs = {x.name: x for x in vim.buffers} |
| 651 |
defs_per_buf = {} |
| 652 |
for name in names: |
| 653 |
try: |
| 654 |
buf = bufs[str(name.module_path)] |
| 655 |
except KeyError: |
| 656 |
continue |
| 657 |
defs_per_buf.setdefault(buf, []).append(name) |
| 658 |
|
| 659 |
if IS_NVIM: |
| 660 |
|
| 661 |
buf_src_ids = {} |
| 662 |
for buf, names in defs_per_buf.items(): |
| 663 |
buf_src_ids[buf] = [] |
| 664 |
for name in names: |
| 665 |
src_id = _add_highlighted_name(buf, name) |
| 666 |
buf_src_ids[buf].append(src_id) |
| 667 |
for buf, src_ids in buf_src_ids.items(): |
| 668 |
buf.vars['_jedi_usages_src_ids'] = src_ids |
| 669 |
else: |
| 670 |
for buf, names in defs_per_buf.items(): |
| 671 |
try: |
| 672 |
for name in names: |
| 673 |
_add_highlighted_name(buf, name) |
| 674 |
except vim.error as exc: |
| 675 |
if exc.args[0].startswith('Vim:E275:'): |
| 676 |
|
| 677 |
_pending_names.setdefault(buf.name, []).extend( |
| 678 |
names) |
| 679 |
else: |
| 680 |
highlight_usages_for_vim_win() |
| 681 |
|
| 682 |
|
| 683 |
def _handle_pending_usages_for_buf(): |
| 684 |
"""Add (pending) highlights for the current buffer (Vim with textprops).""" |
| 685 |
buf = vim.current.buffer |
| 686 |
bufname = buf.name |
| 687 |
try: |
| 688 |
buf_names = _pending_names[bufname] |
| 689 |
except KeyError: |
| 690 |
return |
| 691 |
for name in buf_names: |
| 692 |
_add_highlighted_name(buf, name) |
| 693 |
del _pending_names[bufname] |
| 694 |
|
| 695 |
|
| 696 |
def _add_highlighted_name(buf, name): |
| 697 |
lnum = name.line |
| 698 |
start_col = name.column |
| 699 |
|
| 700 |
|
| 701 |
|
| 702 |
if name.type == 'module' and lnum == 1 and start_col == 0: |
| 703 |
return |
| 704 |
|
| 705 |
_placed_names_in_buffers.add(buf) |
| 706 |
|
| 707 |
|
| 708 |
|
| 709 |
|
| 710 |
length = len(name.name) |
| 711 |
if vim_prop_add: |
| 712 |
|
| 713 |
global vim_prop_type_added |
| 714 |
if not vim_prop_type_added: |
| 715 |
vim.eval("prop_type_add('jediUsage', {'highlight': 'jediUsage'})") |
| 716 |
vim_prop_type_added = True |
| 717 |
vim_prop_add(lnum, start_col+1, { |
| 718 |
'type': 'jediUsage', |
| 719 |
'bufnr': buf.number, |
| 720 |
'length': length, |
| 721 |
}) |
| 722 |
return |
| 723 |
|
| 724 |
assert IS_NVIM |
| 725 |
end_col = name.column + length |
| 726 |
src_id = buf.add_highlight('jediUsage', lnum-1, start_col, end_col, |
| 727 |
src_id=0) |
| 728 |
return src_id |
| 729 |
|
| 730 |
|
| 731 |
def highlight_usages_for_vim_win(): |
| 732 |
"""Highlight usages in the current window. |
| 733 |
|
| 734 |
It stores the matchids in a window-local variable. |
| 735 |
|
| 736 |
(matchaddpos() only works for the current window.) |
| 737 |
""" |
| 738 |
win = vim.current.window |
| 739 |
|
| 740 |
cur_matchids = win.vars.get('_jedi_usages_vim_matchids') |
| 741 |
if cur_matchids: |
| 742 |
if cur_matchids[0] == vim.current.buffer.number: |
| 743 |
return |
| 744 |
|
| 745 |
|
| 746 |
for matchid in cur_matchids[1:]: |
| 747 |
expr = 'matchdelete(%d)' % int(matchid) |
| 748 |
vim.eval(expr) |
| 749 |
|
| 750 |
matchids = [] |
| 751 |
if _current_names: |
| 752 |
buffer_path = vim.current.buffer.name |
| 753 |
for name in _current_names: |
| 754 |
if (str(name.module_path) or '') == buffer_path: |
| 755 |
positions = [ |
| 756 |
[name.line, |
| 757 |
name.column + 1, |
| 758 |
len(name.name)] |
| 759 |
] |
| 760 |
expr = "matchaddpos('jediUsage', %s)" % repr(positions) |
| 761 |
matchids.append(int(vim_eval(expr))) |
| 762 |
|
| 763 |
if matchids: |
| 764 |
vim.current.window.vars['_jedi_usages_vim_matchids'] = [ |
| 765 |
vim.current.buffer.number] + matchids |
| 766 |
elif cur_matchids is not None: |
| 767 |
|
| 768 |
|
| 769 |
vim.current.window.vars['_jedi_usages_vim_matchids'] = [] |
| 770 |
|
| 771 |
|
| 772 |
vim.current.buffer.vars['_jedi_usages_needs_clear'] = bool(matchids) |
| 773 |
|
| 774 |
|
| 775 |
@_check_jedi_availability(show_error=True) |
| 776 |
@catch_and_print_exceptions |
| 777 |
def show_documentation(): |
| 778 |
script = get_script() |
| 779 |
try: |
| 780 |
names = script.help(*get_pos()) |
| 781 |
except Exception: |
| 782 |
|
| 783 |
names = [] |
| 784 |
print("Exception, this shouldn't happen.") |
| 785 |
print(traceback.format_exc()) |
| 786 |
|
| 787 |
if not names: |
| 788 |
echo_highlight('No documentation found for that.') |
| 789 |
vim.command('return') |
| 790 |
return |
| 791 |
|
| 792 |
docs = [] |
| 793 |
for n in names: |
| 794 |
doc = n.docstring() |
| 795 |
if doc: |
| 796 |
title = 'Docstring for %s %s' % (n.type, n.full_name or n.name) |
| 797 |
underline = '=' * len(title) |
| 798 |
docs.append('%s\n%s\n%s' % (title, underline, doc)) |
| 799 |
else: |
| 800 |
docs.append('|No Docstring for %s|' % n) |
| 801 |
text = ('\n' + '-' * 79 + '\n').join(docs) |
| 802 |
vim.command('let l:doc = %s' % repr(PythonToVimStr(text))) |
| 803 |
vim.command('let l:doc_lines = %s' % len(text.split('\n'))) |
| 804 |
return True |
| 805 |
|
| 806 |
|
| 807 |
@catch_and_print_exceptions |
| 808 |
def clear_call_signatures(): |
| 809 |
|
| 810 |
if int(vim_eval("g:jedi#show_call_signatures")) == 2: |
| 811 |
vim_command('echo ""') |
| 812 |
return |
| 813 |
cursor = vim.current.window.cursor |
| 814 |
e = vim_eval('g:jedi#call_signature_escape') |
| 815 |
|
| 816 |
|
| 817 |
|
| 818 |
|
| 819 |
py_regex = r'%sjedi=([0-9]+), (.*?)%s.*?%sjedi%s'.replace( |
| 820 |
'%s', re.escape(e)) |
| 821 |
for i, line in enumerate(vim.current.buffer): |
| 822 |
match = re.search(py_regex, line) |
| 823 |
if match is not None: |
| 824 |
|
| 825 |
|
| 826 |
|
| 827 |
after = line[match.end() + int(match.group(1)):] |
| 828 |
line = line[:match.start()] + match.group(2) + after |
| 829 |
vim.current.buffer[i] = line |
| 830 |
vim.current.window.cursor = cursor |
| 831 |
|
| 832 |
|
| 833 |
@_check_jedi_availability(show_error=False) |
| 834 |
@catch_and_print_exceptions |
| 835 |
def show_call_signatures(signatures=()): |
| 836 |
if int(vim_eval("has('conceal') && g:jedi#show_call_signatures")) == 0: |
| 837 |
return |
| 838 |
|
| 839 |
|
| 840 |
|
| 841 |
|
| 842 |
clear_call_signatures() |
| 843 |
if signatures == (): |
| 844 |
signatures = get_script().get_signatures(*get_pos()) |
| 845 |
|
| 846 |
if not signatures: |
| 847 |
return |
| 848 |
|
| 849 |
if int(vim_eval("g:jedi#show_call_signatures")) == 2: |
| 850 |
return cmdline_call_signatures(signatures) |
| 851 |
|
| 852 |
seen_sigs = [] |
| 853 |
for i, signature in enumerate(signatures): |
| 854 |
line, column = signature.bracket_start |
| 855 |
|
| 856 |
line_to_replace = line - i - 1 |
| 857 |
|
| 858 |
insert_column = column - 1 |
| 859 |
if insert_column < 0 or line_to_replace <= 0: |
| 860 |
|
| 861 |
break |
| 862 |
|
| 863 |
|
| 864 |
line = vim_eval("getline(%s)" % line_to_replace) |
| 865 |
|
| 866 |
|
| 867 |
params = [p.description.replace('\n', '').replace('param ', '', 1) |
| 868 |
for p in signature.params] |
| 869 |
try: |
| 870 |
|
| 871 |
params[signature.index] = '*_*%s*_*' % params[signature.index] |
| 872 |
except (IndexError, TypeError): |
| 873 |
pass |
| 874 |
|
| 875 |
|
| 876 |
if params in seen_sigs: |
| 877 |
continue |
| 878 |
seen_sigs.append(params) |
| 879 |
|
| 880 |
|
| 881 |
|
| 882 |
|
| 883 |
|
| 884 |
|
| 885 |
text = " (%s) " % ', '.join(params) |
| 886 |
text = ' ' * (insert_column - len(line)) + text |
| 887 |
end_column = insert_column + len(text) - 2 |
| 888 |
|
| 889 |
|
| 890 |
|
| 891 |
e = vim_eval('g:jedi#call_signature_escape') |
| 892 |
if hasattr(e, 'decode'): |
| 893 |
e = e.decode('UTF-8') |
| 894 |
|
| 895 |
regex = "xjedi=%sx%sxjedix".replace('x', e) |
| 896 |
|
| 897 |
prefix, replace = line[:insert_column], line[insert_column:end_column] |
| 898 |
|
| 899 |
|
| 900 |
|
| 901 |
regex_quotes = r'''\\*["']+''' |
| 902 |
|
| 903 |
|
| 904 |
add = ' '.join(re.findall(regex_quotes, replace)) |
| 905 |
|
| 906 |
if add and replace[0] in ['"', "'"]: |
| 907 |
a = re.search(regex_quotes + '$', prefix) |
| 908 |
add = ('' if a is None else a.group(0)) + add |
| 909 |
|
| 910 |
tup = '%s, %s' % (len(add), replace) |
| 911 |
repl = prefix + (regex % (tup, text)) + add + line[end_column:] |
| 912 |
|
| 913 |
vim_eval('setline(%s, %s)' % (line_to_replace, repr(PythonToVimStr(repl)))) |
| 914 |
|
| 915 |
|
| 916 |
@catch_and_print_exceptions |
| 917 |
def cmdline_call_signatures(signatures): |
| 918 |
def get_params(s): |
| 919 |
return [p.description.replace('\n', '').replace('param ', '', 1) for p in s.params] |
| 920 |
|
| 921 |
def escape(string): |
| 922 |
return string.replace('"', '\\"').replace(r'\n', r'\\n') |
| 923 |
|
| 924 |
def join(): |
| 925 |
return ', '.join(filter(None, (left, center, right))) |
| 926 |
|
| 927 |
def too_long(): |
| 928 |
return len(join()) > max_msg_len |
| 929 |
|
| 930 |
if len(signatures) > 1: |
| 931 |
params = zip_longest(*map(get_params, signatures), fillvalue='_') |
| 932 |
params = ['(' + ', '.join(p) + ')' for p in params] |
| 933 |
else: |
| 934 |
params = get_params(signatures[0]) |
| 935 |
|
| 936 |
index = next(iter(s.index for s in signatures if s.index is not None), None) |
| 937 |
|
| 938 |
|
| 939 |
|
| 940 |
max_msg_len = int(vim_eval('&columns')) - 12 |
| 941 |
if int(vim_eval('&ruler')): |
| 942 |
max_msg_len -= 18 |
| 943 |
max_msg_len -= len(signatures[0].name) + 2 |
| 944 |
|
| 945 |
if max_msg_len < (1 if params else 0): |
| 946 |
return |
| 947 |
elif index is None: |
| 948 |
text = escape(', '.join(params)) |
| 949 |
if params and len(text) > max_msg_len: |
| 950 |
text = ELLIPSIS |
| 951 |
elif max_msg_len < len(ELLIPSIS): |
| 952 |
return |
| 953 |
else: |
| 954 |
left = escape(', '.join(params[:index])) |
| 955 |
center = escape(params[index]) |
| 956 |
right = escape(', '.join(params[index + 1:])) |
| 957 |
while too_long(): |
| 958 |
if left and left != ELLIPSIS: |
| 959 |
left = ELLIPSIS |
| 960 |
continue |
| 961 |
if right and right != ELLIPSIS: |
| 962 |
right = ELLIPSIS |
| 963 |
continue |
| 964 |
if (left or right) and center != ELLIPSIS: |
| 965 |
left = right = None |
| 966 |
center = ELLIPSIS |
| 967 |
continue |
| 968 |
if too_long(): |
| 969 |
|
| 970 |
return |
| 971 |
|
| 972 |
max_num_spaces = max_msg_len |
| 973 |
if index is not None: |
| 974 |
max_num_spaces -= len(join()) |
| 975 |
_, column = signatures[0].bracket_start |
| 976 |
spaces = min(int(vim_eval('g:jedi#first_col +' |
| 977 |
'wincol() - col(".")')) + |
| 978 |
column - len(signatures[0].name), |
| 979 |
max_num_spaces) * ' ' |
| 980 |
|
| 981 |
if index is not None: |
| 982 |
vim_command(' echon "%s" | ' |
| 983 |
'echohl Function | echon "%s" | ' |
| 984 |
'echohl None | echon "(" | ' |
| 985 |
'echohl jediFunction | echon "%s" | ' |
| 986 |
'echohl jediFat | echon "%s" | ' |
| 987 |
'echohl jediFunction | echon "%s" | ' |
| 988 |
'echohl None | echon ")"' |
| 989 |
% (spaces, signatures[0].name, |
| 990 |
left + ', ' if left else '', |
| 991 |
center, ', ' + right if right else '')) |
| 992 |
else: |
| 993 |
vim_command(' echon "%s" | ' |
| 994 |
'echohl Function | echon "%s" | ' |
| 995 |
'echohl None | echon "(%s)"' |
| 996 |
% (spaces, signatures[0].name, text)) |
| 997 |
|
| 998 |
|
| 999 |
@_check_jedi_availability(show_error=True) |
| 1000 |
@catch_and_print_exceptions |
| 1001 |
def rename(delete_word=True): |
| 1002 |
if not int(vim.eval('a:0')): |
| 1003 |
|
| 1004 |
cursor = vim.current.window.cursor |
| 1005 |
changenr = vim.eval('changenr()') |
| 1006 |
vim_command('augroup jedi_rename') |
| 1007 |
vim_command('autocmd InsertLeave <buffer> call jedi#rename' |
| 1008 |
'({}, {}, {})'.format(cursor[0], cursor[1], changenr)) |
| 1009 |
vim_command('augroup END') |
| 1010 |
|
| 1011 |
vim_command("let s:jedi_replace_orig = expand('<cword>')") |
| 1012 |
line = vim_eval('getline(".")') |
| 1013 |
|
| 1014 |
if delete_word: |
| 1015 |
vim_command('normal! diw') |
| 1016 |
else: |
| 1017 |
vim_command('normal! yiwel') |
| 1018 |
|
| 1019 |
if re.match(r'\w+$', line[cursor[1]:]): |
| 1020 |
|
| 1021 |
|
| 1022 |
vim_command('startinsert!') |
| 1023 |
else: |
| 1024 |
vim_command('startinsert') |
| 1025 |
|
| 1026 |
else: |
| 1027 |
|
| 1028 |
vim_command('autocmd! jedi_rename InsertLeave') |
| 1029 |
|
| 1030 |
args = vim.eval('a:000') |
| 1031 |
cursor = tuple(int(x) for x in args[:2]) |
| 1032 |
changenr = args[2] |
| 1033 |
|
| 1034 |
|
| 1035 |
|
| 1036 |
|
| 1037 |
if vim_eval('getline(".")[getpos(".")[2]-1]') != ' ': |
| 1038 |
replace = vim_eval("expand('<cword>')") |
| 1039 |
else: |
| 1040 |
replace = None |
| 1041 |
|
| 1042 |
vim_command('undo {}'.format(changenr)) |
| 1043 |
|
| 1044 |
vim.current.window.cursor = cursor |
| 1045 |
|
| 1046 |
if replace: |
| 1047 |
return do_rename(replace) |
| 1048 |
|
| 1049 |
|
| 1050 |
def rename_visual(use_selected_text_as_prompt_answer=False): |
| 1051 |
orig = vim.eval('getline(".")[(getpos("\'<")[2]-1):getpos("\'>")[2]' |
| 1052 |
'-((&selection ==# "exclusive") ? 2 : 1)]') |
| 1053 |
|
| 1054 |
input_text = "" |
| 1055 |
if use_selected_text_as_prompt_answer: |
| 1056 |
input_text = orig |
| 1057 |
|
| 1058 |
replace = vim.eval( |
| 1059 |
'input("Rename to:", "{}")'.format(PythonToVimStr(input_text)) |
| 1060 |
) |
| 1061 |
do_rename(replace, orig) |
| 1062 |
|
| 1063 |
|
| 1064 |
def do_rename(replace, orig=None): |
| 1065 |
if not len(replace): |
| 1066 |
echo_highlight('No rename possible without name.') |
| 1067 |
return |
| 1068 |
|
| 1069 |
if orig is None: |
| 1070 |
orig = vim_eval('s:jedi_replace_orig') |
| 1071 |
|
| 1072 |
if orig == replace: |
| 1073 |
echo_highlight('Jedi did 0 renames.') |
| 1074 |
return |
| 1075 |
|
| 1076 |
|
| 1077 |
saved_tab = int(vim_eval('tabpagenr()')) |
| 1078 |
saved_win = int(vim_eval('winnr()')) |
| 1079 |
|
| 1080 |
temp_rename = usages(visuals=False) |
| 1081 |
|
| 1082 |
|
| 1083 |
temp_rename = sorted(temp_rename, reverse=True, |
| 1084 |
key=lambda x: (str(x.module_path), x.line, x.column)) |
| 1085 |
buffers = set() |
| 1086 |
for r in temp_rename: |
| 1087 |
if r.in_builtin_module(): |
| 1088 |
continue |
| 1089 |
|
| 1090 |
result = set_buffer(r.module_path) |
| 1091 |
if not result: |
| 1092 |
echo_highlight('Failed to create buffer window for %s!' % (r.module_path)) |
| 1093 |
continue |
| 1094 |
|
| 1095 |
buffers.add(vim.current.buffer.name) |
| 1096 |
|
| 1097 |
|
| 1098 |
r_line = vim.current.buffer[r.line - 1] |
| 1099 |
vim.current.buffer[r.line - 1] = (r_line[:r.column] + replace + |
| 1100 |
r_line[r.column + len(orig):]) |
| 1101 |
|
| 1102 |
|
| 1103 |
vim_command('tabnext {0:d}'.format(saved_tab)) |
| 1104 |
vim_command('{0:d}wincmd w'.format(saved_win)) |
| 1105 |
|
| 1106 |
if len(buffers) > 1: |
| 1107 |
echo_highlight('Jedi did {0:d} renames in {1:d} buffers!'.format( |
| 1108 |
len(temp_rename), len(buffers))) |
| 1109 |
else: |
| 1110 |
echo_highlight('Jedi did {0:d} renames!'.format(len(temp_rename))) |
| 1111 |
|
| 1112 |
|
| 1113 |
@_check_jedi_availability(show_error=True) |
| 1114 |
@catch_and_print_exceptions |
| 1115 |
def py_import(): |
| 1116 |
args = shsplit(vim.eval('a:args')) |
| 1117 |
import_path = args.pop() |
| 1118 |
name = next(get_project().search(import_path), None) |
| 1119 |
if name is None: |
| 1120 |
echo_highlight('Cannot find %s in your project or on sys.path!' % import_path) |
| 1121 |
else: |
| 1122 |
cmd_args = ' '.join([a.replace(' ', '\\ ') for a in args]) |
| 1123 |
_goto_specific_name(name, options=cmd_args) |
| 1124 |
|
| 1125 |
|
| 1126 |
@catch_and_print_exceptions |
| 1127 |
def py_import_completions(): |
| 1128 |
argl = vim.eval('a:argl') |
| 1129 |
if jedi is None: |
| 1130 |
print('Pyimport completion requires jedi module: https://github.com/davidhalter/jedi') |
| 1131 |
comps = [] |
| 1132 |
else: |
| 1133 |
names = get_project().complete_search(argl) |
| 1134 |
comps = [argl + n for n in sorted(set(c.complete for c in names))] |
| 1135 |
vim.command("return '%s'" % '\n'.join(comps)) |
| 1136 |
|
| 1137 |
|
| 1138 |
@catch_and_print_exceptions |
| 1139 |
def set_buffer(path: Optional[Path], options='', using_tagstack=False): |
| 1140 |
""" |
| 1141 |
Opens a new buffer if we have to or does nothing. Returns True in case of |
| 1142 |
success. |
| 1143 |
""" |
| 1144 |
path = str(path or '') |
| 1145 |
|
| 1146 |
if path in (vim.current.buffer.name, os.path.abspath(vim.current.buffer.name)): |
| 1147 |
return True |
| 1148 |
|
| 1149 |
path = relpath(path) |
| 1150 |
|
| 1151 |
if int(vim_eval('g:jedi#use_tabs_not_buffers')) == 1: |
| 1152 |
_tabnew(path, options) |
| 1153 |
elif not vim_eval('g:jedi#use_splits_not_buffers') in [1, '1']: |
| 1154 |
user_split_option = vim_eval('g:jedi#use_splits_not_buffers') |
| 1155 |
split_options = { |
| 1156 |
'top': 'topleft split', |
| 1157 |
'left': 'topleft vsplit', |
| 1158 |
'right': 'botright vsplit', |
| 1159 |
'bottom': 'botright split', |
| 1160 |
'winwidth': 'vs' |
| 1161 |
} |
| 1162 |
if (user_split_option == 'winwidth' and |
| 1163 |
vim.current.window.width <= 2 * int(vim_eval( |
| 1164 |
"&textwidth ? &textwidth : 80"))): |
| 1165 |
split_options['winwidth'] = 'sp' |
| 1166 |
if user_split_option not in split_options: |
| 1167 |
print('Unsupported value for g:jedi#use_splits_not_buffers: {0}. ' |
| 1168 |
'Valid options are: {1}.'.format( |
| 1169 |
user_split_option, ', '.join(split_options.keys()))) |
| 1170 |
else: |
| 1171 |
vim_command(split_options[user_split_option] + " %s" % escape_file_path(path)) |
| 1172 |
else: |
| 1173 |
if int(vim_eval("!&hidden && &modified")) == 1: |
| 1174 |
if not vim_eval("bufname('%')"): |
| 1175 |
echo_highlight('Cannot open a new buffer, use `:set hidden` or save your buffer') |
| 1176 |
return False |
| 1177 |
else: |
| 1178 |
vim_command('w') |
| 1179 |
if using_tagstack: |
| 1180 |
return True |
| 1181 |
vim_command('edit %s %s' % (options, escape_file_path(path))) |
| 1182 |
|
| 1183 |
if int(vim_eval('!exists("g:syntax_on")')) == 1: |
| 1184 |
vim_command('syntax enable') |
| 1185 |
if int(vim_eval("&filetype != 'python'")) == 1: |
| 1186 |
vim_command('set filetype=python') |
| 1187 |
return True |
| 1188 |
|
| 1189 |
|
| 1190 |
@catch_and_print_exceptions |
| 1191 |
def _tabnew(path, options=''): |
| 1192 |
""" |
| 1193 |
Open a file in a new tab or switch to an existing one. |
| 1194 |
|
| 1195 |
:param options: `:tabnew` options, read vim help. |
| 1196 |
""" |
| 1197 |
if int(vim_eval('has("gui")')) == 1: |
| 1198 |
vim_command('tab drop %s %s' % (options, escape_file_path(path))) |
| 1199 |
return |
| 1200 |
|
| 1201 |
for tab_nr in range(int(vim_eval("tabpagenr('$')"))): |
| 1202 |
for buf_nr in vim_eval("tabpagebuflist(%i + 1)" % tab_nr): |
| 1203 |
buf_nr = int(buf_nr) - 1 |
| 1204 |
try: |
| 1205 |
buf_path = vim.buffers[buf_nr].name |
| 1206 |
except (LookupError, ValueError): |
| 1207 |
|
| 1208 |
|
| 1209 |
pass |
| 1210 |
else: |
| 1211 |
if os.path.abspath(buf_path) == os.path.abspath(path): |
| 1212 |
|
| 1213 |
vim_command('tabfirst | tabnext %i' % (tab_nr + 1)) |
| 1214 |
|
| 1215 |
vim_command('exec bufwinnr(%i) . " wincmd w"' % (buf_nr + 1)) |
| 1216 |
break |
| 1217 |
else: |
| 1218 |
continue |
| 1219 |
break |
| 1220 |
else: |
| 1221 |
|
| 1222 |
vim_command('tabnew %s' % escape_file_path(path)) |
| 1223 |
|
| 1224 |
|
| 1225 |
def escape_file_path(path): |
| 1226 |
return path.replace(' ', r'\ ') |
| 1227 |
|
| 1228 |
|
| 1229 |
def print_to_stdout(level, str_out): |
| 1230 |
print(str_out) |