开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 0 Fork 0

killf/python-mode

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
develop
分支 (4)
标签 (81)
develop
last-py2-support
master
gh-pages
0.13.0
0.12.0
0.11.0
last-py2-support
0.10.0
0.9.2
0.9.1
0.9.0
0.8.1
0.8.0
0.7.8b
0.7.7b
0.7.6b
0.7.5b
0.7.4b
0.7.3b
0.7.2b
0.7.1b
0.7.0b
0.6.19
develop
分支 (4)
标签 (81)
develop
last-py2-support
master
gh-pages
0.13.0
0.12.0
0.11.0
last-py2-support
0.10.0
0.9.2
0.9.1
0.9.0
0.8.1
0.8.0
0.7.8b
0.7.7b
0.7.6b
0.7.5b
0.7.4b
0.7.3b
0.7.2b
0.7.1b
0.7.0b
0.6.19
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
develop
分支 (4)
标签 (81)
develop
last-py2-support
master
gh-pages
0.13.0
0.12.0
0.11.0
last-py2-support
0.10.0
0.9.2
0.9.1
0.9.0
0.8.1
0.8.0
0.7.8b
0.7.7b
0.7.6b
0.7.5b
0.7.4b
0.7.3b
0.7.2b
0.7.1b
0.7.0b
0.6.19
python-mode
/
pymode
/
rope.py
python-mode
/
pymode
/
rope.py
rope.py 24.99 KB
一键复制 编辑 原始数据 按行查看 历史
Andrei Vacariu 提交于 2019年12月07日 07:41 +08:00 . Remove future import in rope.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
"""Integration with Rope library."""
import os.path
import re
import site
import sys
from rope.base import project, libutils, exceptions, change, worder, pycore
from rope.base.fscommands import FileSystemCommands # noqa
from rope.base.taskhandle import TaskHandle # noqa
from rope.contrib import autoimport as rope_autoimport, codeassist, findit, generate # noqa
from rope.refactor import ModuleToPackage, ImportOrganizer, rename, extract, inline, usefunction, move, change_signature, importutils # noqa
from .environment import env
def look_ropeproject(path):
"""Search for ropeproject in current and parent dirs.
:return str|None: A finded path
"""
env.debug('Look project', path)
p = os.path.abspath(path)
while True:
if '.ropeproject' in os.listdir(p):
return p
new_p = os.path.abspath(os.path.join(p, ".."))
if new_p == p:
return path
p = new_p
@env.catch_exceptions
def completions():
""" Search completions.
:return None:
"""
row, col = env.cursor
if env.var('a:findstart', True):
count = 0
for char in reversed(env.current.line[:col]):
if not re.match(r'[\w\d]', char):
break
count += 1
env.debug('Complete find start', (col - count))
return env.stop(col - count)
base = env.var('a:base')
source, offset = env.get_offset_params((row, col), base)
proposals = get_proporsals(source, offset, base)
return env.stop(proposals)
FROM_RE = re.compile(r'^\s*from\s+[\.\w\d_]+$')
@env.catch_exceptions
def complete(dot=False):
""" Ctrl+Space completion.
:return bool: success
"""
row, col = env.cursor
source, offset = env.get_offset_params()
cline = env.current.line[:col]
env.debug('dot completion', cline)
if FROM_RE.match(cline) or cline.endswith('..') or cline.endswith('\.'): # noqa
return env.stop("")
proposals = get_proporsals(source, offset, dot=dot)
if not proposals:
return False
prefix = proposals[0]['word']
# Find common part
for p in proposals:
common = len([
c1 for c1, c2 in zip(prefix, p['word']) if c1 == c2 and c1 != ' '
])
prefix = prefix[:common]
s_offset = codeassist.starting_offset(source, offset)
p_prefix = prefix[offset - s_offset:]
line = env.lines[row - 1]
cline = line[:col] + p_prefix + line[col:]
if cline != line:
if 'noinsert' not in env.var('&completeopt'):
env.curbuf[row - 1] = env.prepare_value(cline, dumps=False)
env.current.window.cursor = (row, col + len(p_prefix))
env.run('complete', col - len(prefix) + len(p_prefix) + 1, proposals)
return True
def get_proporsals(source, offset, base='', dot=False):
""" Code assist.
:return str:
"""
with RopeContext() as ctx: # noqa
try:
proposals = codeassist.code_assist(
ctx.project, source, offset, ctx.resource, maxfixes=3,
later_locals=False)
except exceptions.ModuleSyntaxError:
proposals = []
proposals = sorted(proposals, key=_sort_proporsals)
out = []
preview = 'preview' in ctx.options.get('completeopt')
for p in proposals:
out.append(dict(
word=p.name,
menu=p.type,
kind=p.scope + ':',
info=p.get_doc() or "No docs." if preview else "",
))
out = _get_autoimport_proposals(out, ctx, source, offset, dot=dot)
return out
@env.catch_exceptions
def goto():
""" Goto definition. """
with RopeContext() as ctx:
source, offset = env.get_offset_params()
found_resource, line = codeassist.get_definition_location(
ctx.project, source, offset, ctx.resource, maxfixes=3)
if not found_resource:
env.error('Definition not found')
return
env.goto_file(
found_resource.real_path,
cmd=ctx.options.get('goto_definition_cmd'))
env.goto_line(line)
@env.catch_exceptions
def show_doc():
""" Show documentation. """
with RopeContext() as ctx:
source, offset = env.get_offset_params()
try:
doc = codeassist.get_doc(
ctx.project, source, offset, ctx.resource, maxfixes=3)
if not doc:
raise exceptions.BadIdentifierError
env.let('l:output', doc.split('\n'))
except exceptions.BadIdentifierError:
env.error("No documentation found.")
def find_it():
""" Find occurrences. """
with RopeContext() as ctx:
_, offset = env.get_offset_params()
try:
occurrences = findit.find_occurrences(
ctx.project, ctx.resource, offset)
except exceptions.BadIdentifierError:
occurrences = []
lst = []
for oc in occurrences:
lst.append(dict(
filename=oc.resource.path,
text=env.lines[oc.lineno - 1] if oc.resource.real_path == env.curbuf.name else "", # noqa
lnum=oc.lineno,
type=''
))
env.run('g:PymodeLocList.current().extend', lst)
def update_python_path(paths):
""" Update sys.path and make sure the new items come first. """
old_sys_path_items = list(sys.path)
for path in paths:
# see if it is a site dir
if path.find('site-packages') != -1:
site.addsitedir(path)
else:
sys.path.insert(0, path)
# Reorder sys.path so new directories at the front.
new_sys_path_items = set(sys.path) - set(old_sys_path_items)
sys.path = list(new_sys_path_items) + old_sys_path_items
def organize_imports():
""" Organize imports in current file. """
with RopeContext() as ctx:
organizer = ImportOrganizer(ctx.project)
changes = organizer.organize_imports(ctx.resource)
if changes is not None:
progress = ProgressHandler('Organize imports')
ctx.project.do(changes, task_handle=progress.handle)
reload_changes(changes)
@env.catch_exceptions
def regenerate():
""" Clear cache. """
with RopeContext() as ctx:
ctx.project.pycore._invalidate_resource_cache(ctx.resource) # noqa
ctx.importer.generate_cache()
ctx.project.sync()
def new():
""" Create a new project. """
root = None
if env.var('a:0') != '0':
root = env.var('a:1')
else:
default = env.var('g:pymode_rope_project_root')
if not default:
default = env.var('getcwd()')
if sys.platform.startswith('win32'):
default = default.replace('\\', '/')
root = env.var('input("Enter project root: ", "%s")' % default)
ropefolder = env.var('g:pymode_rope_ropefolder')
prj = project.Project(projectroot=root, ropefolder=ropefolder)
prj.close()
env.message("Project is opened: %s" % root)
def undo():
""" Undo last changes.
:return bool:
"""
with RopeContext() as ctx:
changes = ctx.project.history.tobe_undone
if changes is None:
env.error('Nothing to undo!')
return False
if env.user_confirm('Undo [%s]?' % str(changes)):
progress = ProgressHandler('Undo %s' % str(changes))
for c in ctx.project.history.undo(task_handle=progress.handle):
reload_changes(c)
def redo():
""" Redo last changes.
:return bool:
"""
with RopeContext() as ctx:
changes = ctx.project.history.tobe_redone
if changes is None:
env.error('Nothing to redo!')
return False
if env.user_confirm('Redo [%s]?' % str(changes)):
progress = ProgressHandler('Redo %s' % str(changes))
for c in ctx.project.history.redo(task_handle=progress.handle):
reload_changes(c)
def cache_project(cls):
""" Cache projects.
:return func:
"""
projects = dict()
resources = dict()
def get_ctx(*args, **kwargs):
path = env.curbuf.name
if resources.get(path):
return resources.get(path)
project_path = env.var('g:pymode_rope_project_root')
if not project_path:
project_path = env.curdir
env.debug('Look ctx', project_path)
if env.var('g:pymode_rope_lookup_project', True):
project_path = look_ropeproject(project_path)
if not os.path.exists(project_path):
env.error("Rope project root not exist: %s" % project_path)
ctx = None
else:
ctx = projects.get(project_path)
if not ctx:
projects[project_path] = ctx = cls(path, project_path)
resources[path] = ctx
return ctx
return get_ctx
def autoimport():
""" Autoimport modules.
:return bool:
"""
word = env.var('a:word')
if not word:
env.error("Should be word under cursor.")
return False
with RopeContext() as ctx:
if not ctx.importer.names:
ctx.generate_autoimport_cache()
modules = ctx.importer.get_modules(word)
if not modules:
env.message('Global name %s not found.' % word)
return False
if len(modules) == 1:
_insert_import(word, modules[0], ctx)
else:
module = env.user_input_choices(
'Which module to import:', *modules)
_insert_import(word, module, ctx)
return True
@cache_project
class RopeContext(object):
""" A context manager to have a rope project context. """
projects = {}
resource = {}
def __init__(self, path=None, project_path=None):
""" Init Rope context. """
self.path = path
self.project = project.Project(project_path, fscommands=FileSystemCommands())
self.importer = rope_autoimport.AutoImport(
project=self.project, observe=False)
update_python_path(self.project.prefs.get('python_path', []))
self.resource = None
self.current = None
self.options = dict(
completeopt=env.var('&completeopt'),
autoimport=env.var('g:pymode_rope_autoimport', True),
autoimport_modules=env.var('g:pymode_rope_autoimport_modules'),
goto_definition_cmd=env.var('g:pymode_rope_goto_definition_cmd'),
)
if os.path.exists("%s/__init__.py" % project_path):
sys.path.append(project_path)
if self.options.get('autoimport'):
self.generate_autoimport_cache()
env.debug('Context init', project_path)
env.message('Init Rope project: %s' % project_path)
def __enter__(self):
""" Enter to Rope ctx. """
env.let('g:pymode_rope_current', self.project.root.real_path)
self.project.validate(self.project.root)
self.resource = libutils.path_to_resource(
self.project, env.curbuf.name, 'file')
if not self.resource.exists() or os.path.isdir(
self.resource.real_path):
self.resource = None
else:
env.debug('Found resource', self.resource.path)
return self
def __exit__(self, t, value, traceback):
""" Exit from Rope ctx. """
if t is None:
self.project.close()
def generate_autoimport_cache(self):
""" Update autoimport cache. """
env.message('Regenerate autoimport cache.')
modules = self.options.get('autoimport_modules', [])
def _update_cache(importer, modules=None):
importer.generate_cache()
if modules:
importer.generate_modules_cache(modules)
importer.project.sync()
_update_cache(self.importer, modules)
class ProgressHandler(object):
""" Handle task progress. """
def __init__(self, msg):
""" Init progress handler. """
self.handle = TaskHandle(name="refactoring_handle")
self.handle.add_observer(self)
self.message = msg
def __call__(self):
""" Show current progress. """
percent_done = self.handle.current_jobset().get_percent_done()
env.message('%s - done %s%%' % (self.message, percent_done))
_scope_weight = {
'local': 10, 'attribute': 20, 'global': 30, 'imported': 40, 'builtin': 50}
def _sort_proporsals(p):
return (
_scope_weight.get(p.scope, 100), int(p.name.startswith('_')), p.name)
class Refactoring(object): # noqa
""" Base class for refactor operations. """
def run(self):
""" Run refactoring.
:return bool:
"""
with RopeContext() as ctx:
if not ctx.resource:
env.error("You should save the file before refactoring.")
return None
try:
env.message(self.__doc__)
refactor = self.get_refactor(ctx)
input_str = self.get_input_str(refactor, ctx)
if not input_str:
return False
action = env.user_input_choices(
'Choose what to do:', 'perform', 'preview',
'perform in class hierarchy',
'preview in class hierarchy')
in_hierarchy = action.endswith("in class hierarchy")
changes = self.get_changes(refactor, input_str, in_hierarchy)
if not action:
return False
if action.startswith('preview'):
print("\n ")
print("-------------------------------")
print("\n%s\n" % changes.get_description())
print("-------------------------------\n\n")
if not env.user_confirm('Do the changes?'):
return False
progress = ProgressHandler('Apply changes ...')
ctx.project.do(changes, task_handle=progress.handle)
reload_changes(changes)
except exceptions.RefactoringError as e:
env.error(str(e))
except Exception as e: # noqa
env.error('Unhandled exception in Pymode: %s' % e)
@staticmethod
def get_refactor(ctx):
""" Get refactor object. """
raise NotImplementedError
@staticmethod
def get_input_str(refactor, ctx):
""" Get user input. Skip by default.
:return bool: True
"""
return True
@staticmethod
def get_changes(refactor, input_str, in_hierarchy=False):
return refactor.get_changes(input_str)
class RenameRefactoring(Refactoring):
""" Rename var/function/method/class. """
def __init__(self, module=False):
self.module = module
super(RenameRefactoring, self).__init__()
def get_refactor(self, ctx):
""" Function description.
:return Rename:
"""
offset = None
if not self.module:
_, offset = env.get_offset_params()
env.debug('Prepare rename', offset)
return rename.Rename(ctx.project, ctx.resource, offset)
def get_input_str(self, refactor, ctx):
""" Return user input. """
oldname = str(refactor.get_old_name())
msg = 'Renaming method/variable. New name:'
if self.module:
msg = 'Renaming module. New name:'
newname = env.user_input(msg, oldname)
if newname == oldname:
env.message("Nothing to do.")
return False
return newname
@staticmethod
def get_changes(refactor, input_str, in_hierarchy=False):
""" Get changes.
:return Changes:
"""
return refactor.get_changes(input_str, in_hierarchy=in_hierarchy)
class ExtractMethodRefactoring(Refactoring):
""" Extract method. """
@staticmethod
def get_input_str(refactor, ctx):
""" Return user input. """
return env.user_input('New method name:')
@staticmethod
def get_refactor(ctx):
""" Function description.
:return Rename:
"""
cursor1, cursor2 = env.curbuf.mark('<'), env.curbuf.mark('>')
_, offset1 = env.get_offset_params(cursor1)
_, offset2 = env.get_offset_params(cursor2)
return extract.ExtractMethod(
ctx.project, ctx.resource, offset1, offset2 + 1)
class ExtractVariableRefactoring(Refactoring):
""" Extract variable. """
@staticmethod
def get_input_str(refactor, ctx):
""" Return user input. """
return env.user_input('New variable name:')
@staticmethod
def get_refactor(ctx):
""" Function description.
:return Rename:
"""
cursor1, cursor2 = env.curbuf.mark('<'), env.curbuf.mark('>')
_, offset1 = env.get_offset_params(cursor1)
_, offset2 = env.get_offset_params(cursor2)
return extract.ExtractVariable(
ctx.project, ctx.resource, offset1, offset2 + 1)
class InlineRefactoring(Refactoring):
""" Inline variable/method. """
@staticmethod
def get_refactor(ctx):
""" Function description.
:return Rename:
"""
_, offset = env.get_offset_params()
return inline.create_inline(ctx.project, ctx.resource, offset)
@staticmethod
def get_changes(refactor, input_str, in_hierarchy=False):
""" Get changes.
:return Changes:
"""
return refactor.get_changes()
class UseFunctionRefactoring(Refactoring):
""" Use selected function as possible. """
@staticmethod
def get_refactor(ctx):
""" Function description.
:return Rename:
"""
_, offset = env.get_offset_params()
return usefunction.UseFunction(ctx.project, ctx.resource, offset)
@staticmethod
def get_changes(refactor, input_str, in_hierarchy=False):
""" Get changes.
:return Changes:
"""
return refactor.get_changes()
class ModuleToPackageRefactoring(Refactoring):
""" Convert module to package. """
@staticmethod
def get_refactor(ctx):
""" Function description.
:return Rename:
"""
return ModuleToPackage(ctx.project, ctx.resource)
@staticmethod
def get_changes(refactor, input_str, in_hierarchy=False):
""" Get changes.
:return Changes:
"""
return refactor.get_changes()
class MoveRefactoring(Refactoring):
""" Move method/module to other class/global. """
@staticmethod
def get_input_str(refactor, ctx):
""" Get destination.
:return str:
"""
return env.user_input('Enter destination:')
@staticmethod
def get_refactor(ctx):
""" Function description.
:return Rename:
"""
_, offset = env.get_offset_params()
if offset == 0:
offset = None
return move.create_move(ctx.project, ctx.resource, offset)
class ChangeSignatureRefactoring(Refactoring):
""" Change function signature (add/remove/sort arguments). """
@staticmethod
def get_input_str(refactor, ctx):
""" Get destination.
:return str:
"""
args = refactor.get_args()
default = ', '.join(a[0] for a in args)
return env.user_input('Change the signature:', default)
@staticmethod
def get_refactor(ctx):
""" Function description.
:return Rename:
"""
_, offset = env.get_offset_params()
return change_signature.ChangeSignature(
ctx.project, ctx.resource, offset)
def get_changes(self, refactor, input_string, in_hierarchy=False):
""" Function description.
:return Rope.changes:
"""
args = re.sub(r'[\s\(\)]+', '', input_string).split(',')
olds = [arg[0] for arg in refactor.get_args()]
changers = []
for arg in [a for a in olds if a not in args]:
changers.append(change_signature.ArgumentRemover(olds.index(arg)))
olds.remove(arg)
order = []
for index, arg in enumerate(args):
if arg not in olds:
changers.append(change_signature.ArgumentAdder(index, arg))
olds.insert(index, arg)
order.append(olds.index(arg))
changers.append(change_signature.ArgumentReorderer(
order, autodef='None'))
return refactor.get_changes(changers, in_hierarchy=in_hierarchy)
class GenerateElementRefactoring(Refactoring):
""" Class description. """
def __init__(self, kind, *args, **kwargs):
""" Function description. """
self.kind = kind
super(GenerateElementRefactoring, self).__init__(*args, **kwargs)
def get_refactor(self, ctx):
""" Function description.
:return Rename:
"""
_, offset = env.get_offset_params()
return generate.create_generate(
self.kind, ctx.project, ctx.resource, offset)
def get_changes(self, refactor, input_str, in_hierarchy=False):
""" Function description.
:return Rope.changes:
"""
return refactor.get_changes()
@env.catch_exceptions
def reload_changes(changes):
""" Reload changed buffers. """
resources = changes.get_changed_resources()
moved = _get_moved_resources(changes) # noqa
current = env.curbuf.number
for f in resources:
bufnr = env.var('bufnr("%s")' % f.real_path)
env.goto_buffer(bufnr)
path = env.curbuf.name
if f in moved:
path = moved[f].real_path
env.debug('Reload', f.real_path, path, bufnr)
env.goto_file(path, 'e!', force=True)
env.message("%s has been changed." % f.real_path, history=True)
env.goto_buffer(current)
def _get_moved_resources(changes):
moved = dict()
if isinstance(changes, change.ChangeSet):
for c in changes.changes:
moved.update(_get_moved_resources(c))
if isinstance(changes, change.MoveResource):
moved[changes.resource] = changes.new_resource
return moved
def _get_autoimport_proposals(out, ctx, source, offset, dot=False):
if not ctx.options.get('autoimport') or dot:
return out
if '.' in codeassist.starting_expression(source, offset):
return out
current_offset = offset - 1
while current_offset > 0 and (
source[current_offset].isalnum() or source[current_offset] == '_'):
current_offset -= 1
starting = source[current_offset:offset]
starting = starting.strip()
if not starting:
return out
for assist in ctx.importer.import_assist(starting):
out.append(dict(
abbr=' : '.join(assist),
word=assist[0],
kind='autoimport:',
))
return out
@env.catch_exceptions
def complete_check():
""" Function description.
:return bool:
"""
row, column = env.cursor
line = env.lines[row - 1]
word_finder = worder.Worder(line, True)
parent, name, _ = word_finder.get_splitted_primary_before(column - 1)
if parent:
return False
with RopeContext() as ctx:
modules = ctx.importer.get_modules(name)
if not modules:
return False
if name in ctx.project.pycore.resource_to_pyobject(ctx.resource):
return False
if not env.user_confirm("Import %s?" % name, True):
return False
if len(modules) == 1:
_insert_import(name, modules[0], ctx)
else:
module = env.user_input_choices('With module to import:', *modules)
if module:
_insert_import(name, module, ctx)
def _insert_import(name, module, ctx):
if not ctx.resource:
source, _ = env.get_offset_params()
lineno = ctx.importer.find_insertion_line(source)
line = 'from %s import %s' % (module, name)
env.curbuf[lineno - 1:lineno - 1] = [
env.prepare_value(line, dumps=False)]
return True
pyobject = ctx.project.pycore.resource_to_pyobject(ctx.resource)
import_tools = importutils.ImportTools(ctx.project)
module_imports = import_tools.module_imports(pyobject)
new_import = importutils.FromImport(module, 0, [[name, None]])
module_imports.add_import(new_import)
changes = change.ChangeContents(
ctx.resource, module_imports.get_changed_source())
action = env.user_input_choices(
'Choose what to do:', 'perform', 'preview')
if not action:
return False
if action == 'preview':
print("\n ")
print("-------------------------------")
print("\n%s\n" % changes.get_description())
print("-------------------------------\n\n")
if not env.user_confirm('Do the changes?'):
return False
progress = ProgressHandler('Apply changes ...')
ctx.project.do(changes, task_handle=progress.handle)
reload_changes(changes)
# Monkey patch Rope
def find_source_folders(self, folder):
"""Look only python files an packages."""
for resource in folder.get_folders():
if self._is_package(resource): # noqa
return [folder]
for resource in folder.get_files():
if resource.name.endswith('.py'):
return [folder]
return []
pycore.PyCore._find_source_folders = find_source_folders # noqa
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

暂无描述
暂无标签
LGPL-3.0
使用 LGPL-3.0 开源许可协议
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/killf/python-mode.git
git@gitee.com:killf/python-mode.git
killf
python-mode
python-mode
develop
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /