Beispiel #1
0
    def run(self, edit):
        cxt = op.edit_cxt_for[self.view]
        reg = op.edit_region_for[self.view]

        if cxt.adding_new:
            with op.quitting_edit_mode(self.view):
                self.view.erase(edit, end_plus_1(reg))
                return

        body = op.module_body(self.view)
        entry = body.entry_under_edit()

        if entry.is_def_under_edit():
            defn = comm.op('getDefinition', {
                'module': op.view_module_name(self.view),
                'name': entry.name()
            })
            with op.quitting_edit_mode(self.view):
                self.view.replace(edit, reg, defn)
        elif entry.is_name_under_edit():
            name = comm.op('getNameAt', {
                'module': op.view_module_name(self.view),
                'at': entry.myindex
            })
            with op.quitting_edit_mode(self.view):
                self.view.replace(edit, reg, name)
        else:
            raise RuntimeError
Beispiel #2
0
    def run(self, edit):
        remove = sublime.ok_cancel_dialog(
            "Remove module '{}'?".format(op.view_module_name(self.view))
        )
        if not remove:
            return

        res = comm.op('removeModule', {
            'module': op.view_module_name(self.view),
            'force': False
        })
        if res is not True:
            remove = sublime.ok_cancel_dialog(
                "Module '{}' is connected with these modules: {}. Force removal?".format(
                    op.view_module_name(self.view), ', '.join(res)
                )
            )
            if not remove:
                return

            res = comm.op('removeModule', {
                'module': op.view_module_name(self.view),
                'force': True
            })
            if res is not True:
                sublime.error_message("Could not delete module, returned: {}".format(res))
                return

        file_name = self.view.file_name()
        self.view.close()
        os.unlink(file_name)
Beispiel #3
0
    def run(self, edit):
        if regedit.is_active_in(self.view):
            ok = sublime.ok_cancel_dialog("Unsaved changes would be lost. Continue?")
            if not ok:
                return
            op.terminate_edit_mode(self.view)

        comm.op('refreshModule', {'module': op.view_module_name(self.view)})
Beispiel #4
0
 def run(self, edit, module_name):
     comm.op('renameModule', {
         'module': op.view_module_name(self.view),
         'newName': module_name
     })
     new_file_name = op.module_filename(module_name, op.view_lang(self.view))
     os.rename(self.view.file_name(), new_file_name)
     self.view.retarget(new_file_name)
Beispiel #5
0
    def run(self, edit, entry, alias):
        module_name, entry_name = entry

        comm.op('import', {
            'recp': op.view_module_name(self.view),
            'donor': module_name,
            'name': entry_name,
            'alias': alias,
        })
Beispiel #6
0
 def run(self, edit, direction):
     body = op.module_body(self.view)
     loc = body.cursor_location_or_stop(single_selected_region(self.view),
                                        require_fully_selected=True)
     comm.op(
         'moveBy1', {
             'module': op.view_module_name(self.view),
             'name': loc.entry.name(),
             'direction': direction
         })
Beispiel #7
0
    def run(self, edit):
        edit_region = op.edit_region_for[self.view]
        cxt = op.edit_cxt_for[self.view]
        body = op.module_body(self.view)

        if cxt.adding_new:
            index = body.remove_ephemeral_entry()
            templ = op.RE_FULL_ENTRY[op.view_lang(self.view)]
            
            mtch = re.search(templ, self.view.substr(edit_region), re.DOTALL)

            if mtch is None:
                sublime.status_message("Invalid entry definition")
                return

            if mtch.group('def').isspace():
                sublime.status_message("Empty definition not allowed")
                return

            comm.op(
                'addEntry',
                {
                    'module': op.view_module_name(self.view),
                    'name': mtch.group('name'),
                    'def': mtch.group('def'),
                    'index': index
                },
                committing_module_name=op.view_module_name(self.view)
            )
            return

        entry = body.entry_under_edit()

        if entry.is_def_under_edit():
            res = comm.op(
                'editEntry',
                {
                    'module': op.view_module_name(self.view),
                    'name': entry.name(),
                    'newDef': self.view.substr(edit_region)
                },
                committing_module_name=op.view_module_name(self.view)
            )
        elif entry.is_name_under_edit():
            comm.op(
                'renameEntry',
                {
                    'module': op.view_module_name(self.view),
                    'index': entry.myindex,
                    'newName': self.view.substr(edit_region)
                },
                committing_module_name=op.view_module_name(self.view)
            )
        else:
            raise RuntimeError
Beispiel #8
0
    def run(self, module_name, lang):
        try:
            with open(op.module_filename(module_name, lang), 'x') as file:
                file.write('-----\n')
        except FileExistsError:
            sublime.error_message("Module file already exists")

        comm.op('addModule', {
            'module': module_name,
            'lang': lang
        })
        sublime.active_window().open_file(op.module_filename(module_name, lang))
Beispiel #9
0
 def __init__(self, view, args, chain_tail):
     super().__init__(view, chain_tail)
     res = comm.op('getImportables', {'recp': op.view_module_name(view)})
     self.items = [
         ("{} ({})".format(entry or '*', module), [module, entry])
         for module, entry in res
     ]
Beispiel #10
0
 def run(self, edit, imported_as, new_alias):
     data = comm.op('renameImport', {
         'module': op.view_module_name(self.view),
         'importedAs': imported_as,
         'newAlias': new_alias
     })
     op.modify_module(self.view, edit, data)
     op.save_module(self.view)
Beispiel #11
0
 def run(self):
     res = comm.op('removeUnusedImportsInAllModules', {})
     removed_count = res['removedCount']
     
     if removed_count > 0:
         sublime.status_message("Removed {} unused imports".format(removed_count))
     else:
         sublime.status_message("There are no unused imports in any module")
Beispiel #12
0
 def run(self, edit, name, new_name):
     res = comm.op(
         'replaceUsages', {
             'module': op.view_module_name(self.view),
             'name': name,
             'newName': new_name
         })
     op.modify_module(self.view, edit, res)
     op.save_module(self.view)
Beispiel #13
0
        def __init__(self, view, args, chain_tail):
            super().__init__(view, chain_tail)
            dest_module = args['dest_module']
            self.items = comm.op('getModuleEntries', {'module': dest_module})

            src_module, entry = args['src_module_entry']
            if src_module == dest_module:
                self.items.remove(entry)

            if self.items:
                self.items[:0] = [(self.BOTTOM, True), (self.TOP, False)]
Beispiel #14
0
    def run(self, edit):
        reg = single_selected_region(self.view)
        mtch = op.reference_at(self.view, reg)
        if mtch is None:
            star = None
            name = op.word_at(self.view, reg)
        else:
            star, name = mtch.group('star', 'name')

        res = comm.op('findReferences', {
            'module': op.view_module_name(self.view),
            'star': star,
            'name': name
        })
        if res is None:
            sublime.status_message("Unknown reference at point: \"{}\"".format(
                mtch.group()))
            return

        with active_view_preserved(self.view.window()):
            all_views = [
                self.view.window().open_file(op.module_filename(module_name))
                for module_name, entry_name in res
            ]

        def make_location(view, entry_defn_name, reg):
            row, col = view.rowcol(reg.begin())
            return (view.file_name(), "{}.{}".format(op.view_module_name(view),
                                                     entry_defn_name),
                    (row + 1, col + 1))

        def proceed():
            locations = []

            for view, (module_name, entry_name) in zip(all_views, res):
                # We also track to which definition occurences belong. We do this by
                # determining what is the key region with max index which is still fully
                # before the occurence region.
                regkeys = op.name_regions(view)
                k = 0
                entry_defn_name = "(unknown)"
                regs = view.find_all(r'(?<![\w$])\$\.{}\b'.format(entry_name))

                for reg in regs:
                    while k < len(regkeys) and regkeys[k].end() < reg.begin():
                        k += 1
                        entry_defn_name = view.substr(regkeys[k - 1])

                    locations.append(make_location(view, entry_defn_name, reg))

            navigate_to_symbol(sublime.active_window().active_view(), name,
                               locations)

        on_all_views_load(all_views, proceed)
Beispiel #15
0
    def run(self):
        data = comm.op('getEntries', {})

        def proceed(idx):
            if idx == -1:
                return

            module, entry = data[idx]
            op.goto_module_entry(self.window, module, entry)

        self.window.show_quick_panel([[entry, module]
                                      for module, entry in data], proceed)
Beispiel #16
0
    def run(self, edit, callback):
        module_names = comm.op('getModules', {})
        self.view.window().show_quick_panel(module_names, callback)
        (idx, ) = yield

        if idx == -1:
            return

        module_name = module_names[idx]
        poli_cur_module[self.view] = module_name
        reg = active_prompt_reg(self.view)
        with regedit.region_editing_suppressed(self.view):
            self.view.replace(edit, reg, current_prompt(self.view))
Beispiel #17
0
    def run(self, edit):
        res = comm.op('removeUnusedImports', {
            'module': op.view_module_name(self.view)
        })

        new_import_section = res['importSection']
        removed_count = res['removedCount']

        if removed_count > 0:
            op.replace_import_section(self.view, edit, new_import_section)
            op.save_module(self.view)
            sublime.status_message("Removed {} unused imports".format(removed_count))
        else:
            sublime.status_message("There are no unused imports in this module")
Beispiel #18
0
    def on_query_completions(self, prefix, locations):
        if len(locations) != 1:
            return None

        [pt] = locations
        dollar_dot = self.view.substr(
            sublime.Region(pt - len(prefix) - 2, pt - len(prefix)))
        if dollar_dot != "$.":
            return None

        entries = comm.op('getModuleEntries',
                          {'module': poli_cur_module[self.view]})
        return ([(x, x) for x in entries
                 if x.startswith(prefix)], sublime.INHIBIT_WORD_COMPLETIONS)
Beispiel #19
0
    def run(self, edit):
        reg = single_selected_region(self.view)
        if op.reg_import_section(self.view).contains(reg):
            self.view.run_command('poli_remove_this_import', {
                'force': False
            })
            return

        loc = op.module_body(self.view).cursor_location_or_stop(
            reg, require_fully_selected=True
        )
        res = comm.op('removeEntry', {
            'module': op.view_module_name(self.view),
            'entry': loc.entry.name(),
            'force': False
        })
        if not res['removed']:
            remove_anyway = sublime.ok_cancel_dialog(
                "Entry \"{}\" is being referred to. Remove it anyway?".format(
                    loc.entry.name()
                )
            )
            if not remove_anyway:
                return
            res = comm.op('removeEntry', {
                'module': op.view_module_name(self.view),
                'entry': loc.entry.name(),
                'force': True
            })

        if not res['removed']:
            raise RuntimeError

        with read_only_set_to(self.view, False):
            self.view.erase(edit, loc.entry.reg_entry_nl)

        op.save_module(self.view)
Beispiel #20
0
    def run(self, edit, imported_as, force):
        res = comm.op('removeImport', {
            'module': op.view_module_name(self.view),
            'importedAs': imported_as,
            'force': force
        })
        if not res['removed']:
            assert not force  # otherwise it would have removed the import

            remove_anyway = sublime.ok_cancel_dialog(
                "The import \"{}\" is being used. Remove it anyway?".format(imported_as),
                "Remove"
            )
            if not remove_anyway:
                return

            res = comm.op('removeImport', {
                'module': op.view_module_name(self.view),
                'importedAs': imported_as,
                'force': True
            })
        
        op.replace_import_section(self.view, edit, res['importSection'])
        op.save_module(self.view)
Beispiel #21
0
    def run(self, edit):
        if not regedit.is_active_in(self.view):
            return  # Protected by keymap binding

        reg = regedit.editing_region(self.view)
        reg_stripped = end_strip_region(self.view, reg)

        if reg_stripped.empty():
            sublime.status_message("Empty prompt")
            return

        if reg.end() > reg_stripped.end():
            self.view.erase(edit, sublime.Region(reg_stripped.end(),
                                                 reg.end()))
            reg = reg_stripped

        code = self.view.substr(reg)
        try:
            text = comm.op('eval', {
                'module': poli_cur_module[self.view],
                'code': code
            })
            success = True
        except ReplEvalError as e:
            text = e.stack
            success = False

        if success:
            self.view.insert(edit, self.view.size(), '\n< ')
        else:
            self.view.insert(edit, self.view.size(), '\n! ')

        self.view.insert(edit, self.view.size(), text)
        self.view.insert(edit, self.view.size(), '\n')

        insert_prompt_at_end(self.view, edit)

        hns_for.pop(self.view, None)
Beispiel #22
0
    def on_query_completions(self, prefix, locations):
        if not config.enabled:
            return None

        if len(locations) != 1:
            return None

        [pt] = locations
        linereg = self.view.line(pt)
        str_prec = self.view.substr(sublime.Region(linereg.begin(), pt))
        mtch = re.search(r'^.*?\$(?:\.(?P<star>\w+))?\.(?P<prefix>\w+)$',
                         str_prec)
        if mtch is None:
            return None

        entries = comm.op(
            'getCompletions', {
                'module': op.view_module_name(self.view),
                'star': mtch.group('star'),
                'prefix': mtch.group('prefix')
            })

        return ([(x, x) for x in entries], sublime.INHIBIT_WORD_COMPLETIONS
                | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
Beispiel #23
0
 def run(self, edit, donor_module):
     comm.op('convertImportsToStar', {
         'recp': op.view_module_name(self.view),
         'donor': donor_module
     })
Beispiel #24
0
 def __init__(self, view, args, chain_tail):
     module_name, entry = args['entry']
     disallowed_names = comm.op('getModuleNames', {
         'module': op.view_module_name(view)
     })
     super().__init__(view, chain_tail, entry, disallowed_names)
Beispiel #25
0
 def __init__(self, view, args, chain_tail):
     super().__init__(view, chain_tail)
     self.existing_module_names = comm.op('getModules', {})
Beispiel #26
0
 def __init__(self, module):
     self.module = module
     self.names = comm.op('getModuleNames', {'module': module})
Beispiel #27
0
 def __init__(self, view, args, chain_tail):
     super().__init__(view, chain_tail)
     data = comm.op('getEntries', {})
     self.items = [("{} ({})".format(entry, module), [module, entry])
                   for module, entry in data]
Beispiel #28
0
 def __init__(self, view, args, chain_tail):
     super().__init__(view, chain_tail)
     self.items = comm.op('getModules', {})
     self.items.remove(args['src_module_entry'][0])
Beispiel #29
0
    def run(self, src_module_entry, dest_module, anchor, before=None):
        src_module, entry = src_module_entry

        self._check_src_available(src_module, entry)
        self._check_anchor_available(dest_module, anchor)

        res = comm.op(
            'move', {
                'srcModule': src_module,
                'entry': entry,
                'destModule': dest_module,
                'anchor': anchor,
                'before': before
            })

        if not res['moved']:
            msg = ["Failed to move the entry because:\n"]

            if res['offendingRefs']:
                msg.append(
                    "the definition refers to names that could not be imported into "
                    "the destination module: {}".format(', '.join(
                        '$.' + r for r in res['offendingRefs'])))
            if res['blockingReferrers']:
                msg.append(
                    "these modules cannot star-import the entry from the destination "
                    "module: {}".format(', '.join(res['blockingReferrers'])))

            sublime.error_message('\n'.join(msg))
            return

        def process_source(view, edit):
            with regedit.region_editing_suppressed(view):
                entry_obj = op.module_body(view).entry_by_name(entry)
                view.erase(edit, entry_obj.reg_entry_nl)
                op.save_module(view)

        def process_destination(view, edit):
            with regedit.region_editing_suppressed(view):
                if anchor is None:
                    insert_at = op.reg_body(view).begin()
                else:
                    mcont = op.module_body(view)
                    if anchor is False:
                        insert_at = mcont.entries[0].reg_entry_nl.begin()
                    elif anchor is True:
                        insert_at = mcont.entries[-1].reg_entry_nl.end()
                    else:
                        entry_obj = op.module_body(view).entry_by_name(anchor)

                        if before:
                            insert_at = entry_obj.reg_entry_nl.begin()
                        else:
                            insert_at = entry_obj.reg_entry_nl.end()

                view.insert(edit, insert_at,
                            '{} ::= {}\n'.format(entry, res['newCode']))

                op.save_module(view)

        def process_other(view, module_data, edit):
            op.modify_module(view, edit, module_data)
            op.save_module(view)

        def proceed(src_view, dest_view, other_views):
            with exc_recorded() as exc_src:
                call_with_edit(src_view, partial(process_source, src_view))

            with exc_recorded() as exc_dest:
                call_with_edit(dest_view,
                               partial(process_destination, dest_view))

            exc_others = [exc_recorded() for view in other_views]

            for exc, view, module_data in zip(exc_others, other_views,
                                              res['modifiedModules']):
                with exc:
                    call_with_edit(view,
                                   partial(process_other, view, module_data))

            fmodules = {
                op.view_module_name(view)
                for exc, view in zip(exc_others, other_views) if exc
            }
            if exc_src:
                fmodules.add(op.view_module_name(src_view))
            if exc_dest:
                fmodules.add(op.view_module_name(dest_view))

            if fmodules:
                sublime.error_message(
                    "The following modules failed to update (you may consider refreshing "
                    "them from the image): {}".format(', '.join(fmodules)))

                if exc_src:
                    print("Source updating failed:")
                    traceback.print_exception(type(exc_src.exc), exc_src.exc,
                                              None)
                if exc_dest:
                    print("Dest updating failed:")
                    traceback.print_exception(type(exc_dest.exc), exc_dest.exc,
                                              None)
                for view, exc in zip(other_views, exc_others):
                    if not exc:
                        continue
                    print("Modified module \"{}\" updating failed:".format(
                        op.view_module_name(view)))
                    traceback.print_exception(type(exc.exc), exc.exc, None)
            elif res['danglingRefs']:
                sublime.message_dialog(
                    "These references appear to be dangling: {}".format(
                        ','.join('$.' + r for r in res['danglingRefs'])))
            else:
                sublime.status_message("Move succeeded!")

        with active_view_preserved(self.window):
            src_view = self.window.open_file(op.module_filename(src_module))
            dest_view = self.window.open_file(op.module_filename(dest_module))
            other_views = [
                self.window.open_file(op.module_filename(d['module']))
                for d in res['modifiedModules']
            ]

        on_all_views_load([src_view, dest_view] + other_views,
                          lambda: proceed(src_view, dest_view, other_views))