|
| 1 | +import sublime |
| 2 | +import sublime_plugin |
| 3 | +import os |
| 4 | + |
| 5 | +from .command_base import AdvancedNewFileBase |
| 6 | +from ..anf_util import * |
| 7 | + |
| 8 | + |
| 9 | +class AdvancedNewFileCutToFile(AdvancedNewFileBase, sublime_plugin.WindowCommand): |
| 10 | + def __init__(self, window): |
| 11 | + super(AdvancedNewFileCutToFile, self).__init__(window) |
| 12 | + |
| 13 | + def run(self, is_python=False): |
| 14 | + self.is_python = is_python |
| 15 | + self.run_setup() |
| 16 | + self.view.add_regions(REGION_KEY, self.view.sel(), flags=sublime.HIDDEN) |
| 17 | + |
| 18 | + path = self.settings.get(CUT_TO_FILE_DEFAULT_SETTING, "") |
| 19 | + path = self._expand_default_path(path) |
| 20 | + |
| 21 | + self.show_filename_input( |
| 22 | + path if len(path) > 0 else self.generate_initial_path()) |
| 23 | + |
| 24 | + def input_panel_caption(self): |
| 25 | + caption = 'Move selection to' |
| 26 | + if self.is_python: |
| 27 | + caption = '%s (creates __init__.py in new dirs)' % caption |
| 28 | + return caption |
| 29 | + |
| 30 | + def update_status_message(self, creation_path): |
| 31 | + status_base = "Cutting selection to" |
| 32 | + if self.view is not None: |
| 33 | + self.view.set_status("AdvancedNewFile", "%s %s " % |
| 34 | + (status_base, creation_path)) |
| 35 | + else: |
| 36 | + sublime.status_message("%s %s" % (status_base, creation_path)) |
| 37 | + |
| 38 | + def entered_file_action(self, path): |
| 39 | + file_exist = os.path.exists(path) |
| 40 | + attempt_open = True |
| 41 | + if not file_exist: |
| 42 | + attempt_open = self._create_new_file(path) |
| 43 | + if attempt_open: |
| 44 | + self._open_and_add_content_to_file(path) |
| 45 | + self.view.run_command("anf_remove_region_content_and_region", { "region_key": REGION_KEY}) |
| 46 | + self.open_file(path) |
| 47 | + |
| 48 | + |
| 49 | + def _create_new_file(self, path): |
| 50 | + attempt_open = True |
| 51 | + |
| 52 | + try: |
| 53 | + self.create(path) |
| 54 | + except OSError as e: |
| 55 | + attempt_open = False |
| 56 | + sublime.error_message("Cannot create '" + path + |
| 57 | + "'. See console for details") |
| 58 | + return attempt_open |
| 59 | + |
| 60 | + def _open_and_add_content_to_file(self, path): |
| 61 | + if os.path.isfile(path): |
| 62 | + content = "" |
| 63 | + for region in self.view.get_regions(REGION_KEY): |
| 64 | + content += self.view.substr(region) |
| 65 | + content += "\n" |
| 66 | + |
| 67 | + with open(path, "a") as file_obj: |
| 68 | + file_obj.write(content) |
| 69 | + |
| 70 | + def is_enabled(self): |
| 71 | + view = self.window.active_view() |
| 72 | + cursors = view.sel() |
| 73 | + for cursor in cursors: |
| 74 | + if not cursor.empty(): |
| 75 | + return True |
| 76 | + |
| 77 | + return False |
| 78 | + |
0 commit comments