Anonymous avatar Anonymous committed 6fdaf62

ropemacs: removed lisputils

Comments (0)

Files changed (5)

ropecommon/decorators.py

 
 from rope.base import exceptions
 
-from ropecommon import lisputils
+from Pymacs import lisp
 
 
 def lisphook(func):
             func(*args, **kwds)
         except Exception, e:
             trace = str(traceback.format_exc())
-            lisputils.message(
-                '%s\nIgnored an exception in ropemacs hook: %s' %
-                (trace, _exception_message(e)))
+            lisp.message('%s\nIgnored an exception in ropemacs hook: %s' %
+                         (trace, _exception_message(e)))
     newfunc.lisp = None
     newfunc.__name__ = func.__name__
     newfunc.__doc__ = func.__doc__
         try:
             func(*args, **kwds)
         except exceptions.RopeError, e:
-            lisputils.message(str(traceback.format_exc()))
+            lisp.message(str(traceback.format_exc()))
             if isinstance(e, input_exceptions):
-                lisputils.message(_exception_message(e))
+                lisp.message(_exception_message(e))
     newfunc.__name__ = func.__name__
     newfunc.__doc__ = func.__doc__
     return newfunc

ropecommon/interface.py

 from rope.base import libutils
 from rope.contrib import codeassist, generate, autoimport, findit
 
-from ropecommon import refactor, lisputils, decorators, dialog
+from ropecommon import refactor, decorators, dialog
 
 
 class Ropemacs(object):
 
-    def __init__(self):
+    def __init__(self, env):
         self.project = None
         self.old_content = None
+        self.env = env
         lisp(DEFVARS)
 
         self._prepare_refactorings()
                     @decorators.local_command(attr.key, 'P', None, lisp_name)
                     def do_refactor(prefix, self=self, refactoring=attr):
                         initial_asking = prefix is None
-                        refactoring(self).show(initial_asking=initial_asking)
+                        refactoring(self, self.env).show(initial_asking=initial_asking)
                     setattr(self, ref_name, do_refactor)
 
     def _refactoring_name(self, refactoring):
     @decorators.global_command('o')
     def open_project(self, root=None):
         if not root:
-            root = lisputils.ask_directory('Rope project root folder: ')
+            root = self.env.ask_directory('Rope project root folder: ')
         if self.project is not None:
             self.close_project()
-        progress = lisputils.create_progress('Opening "%s" project' % root)
+        progress = self.env.create_progress('Opening "%s" project' % root)
         self.project = rope.base.project.Project(root)
         if lisp['ropemacs-enable-autoimport'].value():
             underlined = lisp['ropemacs-autoimport-underlineds'].value()
     @decorators.global_command('k')
     def close_project(self):
         if self.project is not None:
-            progress = lisputils.create_progress('Closing "%s" project' %
-                                                 self.project.address)
+            progress = self.env.create_progress('Closing "%s" project' %
+                                                self.project.address)
             self.project.close()
             self.project = None
             progress.done()
     @decorators.global_command()
     def write_project(self):
         if self.project is not None:
-            progress = lisputils.create_progress(
+            progress = self.env.create_progress(
                 'Writing "%s" project data to disk' % self.project.address)
             self.project.sync()
             progress.done()
         self._check_project()
         change = self.project.history.tobe_undone
         if change is None:
-            lisputils.message('Nothing to undo!')
+            self.env.message('Nothing to undo!')
             return
         if lisp.y_or_n_p('Undo <%s>? ' % str(change)):
             def undo(handle):
                 for changes in self.project.history.undo(task_handle=handle):
                     self._reload_buffers(changes, undo=True)
-            lisputils.runtask(undo, 'Undo refactoring', interrupts=False)
+            self.env.runtask(undo, 'Undo refactoring', interrupts=False)
 
     @decorators.global_command('r')
     def redo(self):
         self._check_project()
         change = self.project.history.tobe_redone
         if change is None:
-            lisputils.message('Nothing to redo!')
+            self.env.message('Nothing to redo!')
             return
         if lisp.y_or_n_p('Redo <%s>? ' % str(change)):
             def redo(handle):
                 for changes in self.project.history.redo(task_handle=handle):
                     self._reload_buffers(changes)
-            lisputils.runtask(redo, 'Redo refactoring', interrupts=False)
+            self.env.runtask(redo, 'Redo refactoring', interrupts=False)
 
     def _get_region(self):
         offset1 = self._get_offset()
             lisp.push_mark()
             self._goto_location(definition[0], definition[1])
         else:
-            lisputils.message('Cannot find the definition!')
+            self.env.message('Cannot find the definition!')
 
     @decorators.local_command('a d', 'P', 'C-c d')
     def show_doc(self, prefix):
     @decorators.local_command()
     def show_call_doc(self, prefix):
         self._check_project()
-        lisputils.message('ropemacs: use `rope-show-calltip\' instead!')
+        self.env.message('ropemacs: use `rope-show-calltip\' instead!')
 
     def _base_show_doc(self, prefix, get_doc):
         maxfixes = lisp['ropemacs-codeassist-maxfixes'].value()
             use_minibuffer = not use_minibuffer
         if use_minibuffer and docs:
             docs = '\n'.join(docs.split('\n')[:7])
-            lisputils.message(docs)
+            self.env.message(docs)
         else:
             fit_lines = lisp["ropemacs-max-doc-buffer-height"].value()
-            buffer = lisputils.make_buffer('*rope-pydoc*', docs,
-                                           empty_goto=False,
+            buffer = self.env.make_buffer('*rope-pydoc*', docs,
+                                          empty_goto=False,
                                            fit_lines=fit_lines)
             lisp.local_set_key('q', lisp.bury_buffer)
         if docs is None:
-            lisputils.message('No docs avilable!')
+            self.env.message('No docs avilable!')
 
     def _base_findit(self, do_find, optionals, get_kwds):
         self._check_project()
         resource, offset = self._get_location()
 
         action, values = dialog.show_dialog(
-            lisputils.askdata, ['search', 'cancel'], optionals=optionals)
+            self.env.askdata, ['search', 'cancel'], optionals=optionals)
         if action == 'search':
             kwds = get_kwds(values)
             def calculate(handle):
                                                 values.get('resources'))
                 return do_find(self.project, resource, offset,
                                resources=resources, task_handle=handle, **kwds)
-            result = lisputils.runtask(calculate, 'Find Occurrences')
+            result = self.env.runtask(calculate, 'Find Occurrences')
             text = []
             for occurrence in result:
                 line = '%s : %s' % (occurrence.resource.path, occurrence.offset)
                     line += ' ?'
                 text.append(line)
             text = '\n'.join(text) + '\n'
-            buffer = lisputils.make_buffer('*rope-occurrences*',
-                                           text, switch=True)
+            buffer = self.env.make_buffer('*rope-occurrences*',
+                                          text, switch=True)
             lisp.set_buffer(buffer)
             lisp.local_set_key('\r', lisp.rope_occurrences_goto_occurrence)
             lisp.local_set_key('q', lisp.rope_occurrences_quit)
 
     @decorators.interactive
     def occurrences_quit(self):
-        lisputils.hide_buffer('*rope-occurrences*')
+        self.env.hide_buffer('*rope-occurrences*')
 
     @decorators.local_command('a /', 'P', 'M-/')
     def code_assist(self, prefix):
     def _check_autoimport(self):
         self._check_project()
         if self.autoimport is None:
-            lisputils.message('autoimport is disabled; '
-                              'see `ropemacs-enable-autoimport\' variable')
+            self.env.message('autoimport is disabled; '
+                             'see `ropemacs-enable-autoimport\' variable')
             return False
         return True
 
         def generate(handle):
             self.autoimport.generate_cache(task_handle=handle)
             self.autoimport.generate_modules_cache(modules, task_handle=handle)
-        lisputils.runtask(generate, 'Generate autoimport cache')
+        self.env.runtask(generate, 'Generate autoimport cache')
 
     @decorators.global_command('f', 'P')
     def find_file(self, prefix):
         names = []
         for file in files:
             names.append('<'.join(reversed(file.path.split('/'))))
-        result = lisputils.ask_values('Rope Find File: ', names, exact=True)
+        result = self.env.ask_values('Rope Find File: ', names, exact=True)
         if result is not None:
             path = '/'.join(reversed(result.split('<')))
             file = self.project.get_file(path)
             return file
-        lisputils.message('No file selected')
+        self.env.message('No file selected')
 
     @decorators.local_command('a j')
     def jump_to_global(self):
         if not self._check_autoimport():
             return
         all_names = list(self.autoimport.get_all_names())
-        name = lisputils.ask_values('Global name: ', all_names)
+        name = self.env.ask_values('Global name: ', all_names)
         result = dict(self.autoimport.get_name_locations(name))
         if len(result) == 1:
             resource = list(result.keys())[0]
             config = self.project.ropefolder.get_child('config.py')
             lisp.find_file(config.real_path)
         else:
-            lisputils.message('No rope project folder found')
+            self.env.message('No rope project folder found')
 
     @decorators.global_command('n m')
     def create_module(self):
         self._check_project()
         def _analyze_modules(handle):
             libutils.analyze_modules(self.project, task_handle=handle)
-        lisputils.runtask(_analyze_modules, 'Analyze project modules')
+        self.env.runtask(_analyze_modules, 'Analyze project modules')
 
     def _create(self, name, callback, parentname='source'):
         self._check_project()
                 parentname.title() + ' Folder: ',
                 default=self.project.address, kind='directory')}
         action, values = dialog.show_dialog(
-            lisputils.askdata, ['perform', 'cancel'], confs, optionals)
+            self.env.askdata, ['perform', 'cancel'], confs, optionals)
         if action == 'perform':
             parent = libutils.path_to_resource(
                 self.project, values.get(parentname, self.project.address))
             self._starting = common_start
             self._offset = self.starting_offset + len(common_start)
         prompt = 'Completion for %s: ' % self.expression
-        result = lisputils.ask_values(prompt, names,
-                                      starting=self.starting, exact=None)
+        result = self.env.ask_values(prompt, names,
+                                     starting=self.starting, exact=None)
         self._apply_assist(result)
 
     def lucky_assist(self, prefix):
         if 0 <= selected < len(names):
             result = names[selected]
         else:
-            lisputils.message('Not enough proposals!')
+            self.env.message('Not enough proposals!')
             return
         self._apply_assist(result)
 
             if len(modules) == 1:
                 module = modules[0]
             else:
-                module = lisputils.ask_values(
+                module = self.env.ask_values(
                     'Which module to import: ', modules)
             self._insert_import(name, module)
         else:
-            lisputils.message('Global name %s not found!' % name)
+            self.env.message('Global name %s not found!' % name)
 
     def _apply_assist(self, assist):
         if ' : ' in assist:

ropecommon/lisputils.py

-import traceback
-
-from Pymacs import lisp
-from rope.base import taskhandle, exceptions
-
-
-def yes_or_no(prompt):
-    return lisp.yes_or_no_p(prompt)
-
-
-def make_buffer(name, contents, empty_goto=True,
-                switch=False, window='other', modes=[],
-                fit_lines=None):
-    """Make an emacs buffer
-
-    `window` can be one of `None`, 'current' or 'other'.
-
-    """
-    new_buffer = lisp.get_buffer_create(name)
-    lisp.set_buffer(new_buffer)
-    lisp.toggle_read_only(-1)
-    lisp.erase_buffer()
-    if contents or empty_goto:
-        lisp.insert(contents)
-        for mode in modes:
-            lisp[mode + '-mode']()
-        lisp.buffer_disable_undo(new_buffer)
-        lisp.toggle_read_only(1)
-        if switch:
-            if window == 'current':
-                lisp.switch_to_buffer(new_buffer)
-            else:
-                lisp.switch_to_buffer_other_window(new_buffer)
-            lisp.goto_char(lisp.point_min())
-        elif window == 'other':
-            new_window = lisp.display_buffer(new_buffer)
-            lisp.set_window_point(new_window, lisp.point_min())
-            if fit_lines and lisp.fboundp(lisp['fit-window-to-buffer']):
-                lisp.fit_window_to_buffer(new_window, fit_lines)
-                lisp.bury_buffer(new_buffer)
-    return new_buffer
-
-
-def hide_buffer(name, delete=True):
-    buffer = lisp.get_buffer(name)
-    if buffer is not None:
-        window = lisp.get_buffer_window(buffer)
-        if window is not None:
-            lisp.bury_buffer(buffer)
-            if delete:
-                lisp.delete_window(window)
-            else:
-                if lisp.buffer_name(lisp.current_buffer()) == name:
-                    lisp.switch_to_buffer(None)
-
-
-class RunTask(object):
-
-    def __init__(self, task, name, interrupts=True):
-        self.task = task
-        self.name = name
-        self.interrupts = interrupts
-
-    def __call__(self):
-        handle = taskhandle.TaskHandle(name=self.name)
-        progress = create_progress(self.name)
-        def update_progress():
-            jobset = handle.current_jobset()
-            if jobset:
-                percent = jobset.get_percent_done()
-                if percent is not None:
-                    progress.update(percent)
-        handle.add_observer(update_progress)
-        result = self.task(handle)
-        progress.done()
-        return result
-
-
-def runtask(command, name, interrupts=True):
-    return RunTask(command, name, interrupts)()
-
-def create_progress(name):
-    if lisp.fboundp(lisp['make-progress-reporter']):
-        progress = _LispProgress(name)
-    else:
-        progress = _OldProgress(name)
-    return progress
-
-
-class _LispProgress(object):
-
-    def __init__(self, name):
-        self.progress = lisp.make_progress_reporter('%s ... ' % name, 0, 100)
-
-    def update(self, percent):
-        lisp.progress_reporter_update(self.progress, percent)
-
-    def done(self):
-        lisp.progress_reporter_done(self.progress)
-
-class _OldProgress(object):
-
-    def __init__(self, name):
-        self.name = name
-        self.update(0)
-
-    def update(self, percent):
-        if percent != 0:
-            message('%s ... %s%%%%' % (self.name, percent))
-        else:
-            message('%s ... ' % self.name)
-
-    def done(self):
-        message('%s ... done' % self.name)
-
-
-def message(message):
-    lisp.message(message)
-
-
-def askdata(data, starting=None):
-    """`data` is a `ropemacs.dialog.Data` object"""
-    ask_func = ask
-    ask_args = {'prompt': data.prompt, 'starting': starting,
-                'default': data.default}
-    if data.values:
-        ask_func = ask_values
-        ask_args['values'] = data.values
-    elif data.kind == 'directory':
-        ask_func = ask_directory
-    return ask_func(**ask_args)
-
-
-def ask_values(prompt, values, default=None, starting=None, exact=True):
-    if _emacs_version() < 22:
-        values = [[value, value] for value in values]
-    if exact and default is not None:
-        prompt = prompt + ('[%s] ' % default)
-    reader = lisp['ropemacs-completing-read-function'].value()
-    result = reader(prompt, values, None, exact, starting)
-    if result == '' and exact:
-        return default
-    return result
-
-
-def ask(prompt, default=None, starting=None):
-    if default is not None:
-        prompt = prompt + ('[%s] ' % default)
-    result = lisp.read_from_minibuffer(prompt, starting, None, None,
-                                        None, default, None)
-    if result == '' and default is not None:
-        return default
-    return result
-
-def ask_directory(prompt, default=None, starting=None):
-    if default is not None:
-        prompt = prompt + ('[%s] ' % default)
-    if lisp.fboundp(lisp['read-directory-name']):
-        result = lisp.read_directory_name(prompt, starting, default)
-    else:
-        result = lisp.read_file_name(prompt, starting, default)
-    if result == '' and default is not None:
-        return default
-    return result
-
-def _emacs_version():
-    return int(lisp['emacs-version'].value().split('.')[0])

ropecommon/refactor.py

 import rope.refactor.restructure
 import rope.refactor.usefunction
 
-from ropecommon import dialog, lisputils, filter
+from ropecommon import dialog, filter
 
 
 class Refactoring(object):
     optionals = {}
     saveall = True
 
-    def __init__(self, interface):
+    def __init__(self, interface, env):
         self.interface = interface
+        self.env = env
 
     def show(self, initial_asking=True):
         self.interface._check_project()
         self.interface._save_buffers(only_current=not self.saveall)
         self._create_refactoring()
         action, result = dialog.show_dialog(
-            lisputils.askdata, ['perform', 'preview', 'cancel'],
+            self.env.askdata, ['perform', 'preview', 'cancel'],
             self._get_confs(), self._get_optionals(),
             initial_asking=initial_asking)
         if action == 'cancel':
-            lisputils.message('Cancelled!')
+            self.env.message('Cancelled!')
             return
         def calculate(handle):
             return self._calculate_changes(result, handle)
         name = 'Calculating %s changes' % self.name
-        changes = lisputils.runtask(calculate, name=name)
+        changes = self.env.runtask(calculate, name=name)
         if action == 'perform':
             self._perform(changes)
         if action == 'preview':
             if changes is not None:
                 diffs = str(changes.get_description())
-                lisputils.make_buffer('*rope-preview*', diffs, switch=True,
+                self.env.make_buffer('*rope-preview*', diffs, switch=True,
                                       modes=['diff'], window='current')
-                if lisputils.yes_or_no('Do the changes? '):
+                if self.env.yes_or_no('Do the changes? '):
                     self._perform(changes)
                 else:
-                    lisputils.message('Thrown away!')
-                lisputils.hide_buffer('*rope-preview*', delete=False)
+                    self.env.message('Thrown away!')
+                self.env.hide_buffer('*rope-preview*', delete=False)
             else:
-                lisputils.message('No changes!')
+                self.env.message('No changes!')
 
     @property
     def project(self):
 
     def _perform(self, changes):
         if changes is None:
-            lisputils.message('No changes!')
+            self.env.message('No changes!')
             return
         def perform(handle, self=self, changes=changes):
             self.project.do(changes, task_handle=handle)
             self.interface._reload_buffers(changes)
             self._done()
-        lisputils.runtask(perform, 'Making %s changes' % self.name,
+        self.env.runtask(perform, 'Making %s changes' % self.name,
                           interrupts=False)
-        lisputils.message(str(changes.description) + ' finished')
+        self.env.message(str(changes.description) + ' finished')
 
     def _get_confs(self):
         return self.confs
 
     saveall = True
 
-    def __init__(self, interface):
-        self.interface = interface
-
     def _create_refactoring(self):
         self.renamer = rope.refactor.rename.Rename(
             self.project, self.resource, self.offset)
 """ropemacs, an emacs mode for using rope refactoring library"""
+from Pymacs import lisp
+from rope.base import taskhandle
 
 import ropecommon.dialog
 import ropecommon.interface
-import ropecommon.lisputils
-import traceback
 
-from Pymacs import lisp
-from rope.base import taskhandle, exceptions
+
+class LispUtils(object):
+
+    def yes_or_no(self, prompt):
+        return lisp.yes_or_no_p(prompt)
+
+    def make_buffer(self, name, contents, empty_goto=True, switch=False,
+                    window='other', modes=[], fit_lines=None):
+        """Make an emacs buffer
+
+        `window` can be one of `None`, 'current' or 'other'.
+        """
+        new_buffer = lisp.get_buffer_create(name)
+        lisp.set_buffer(new_buffer)
+        lisp.toggle_read_only(-1)
+        lisp.erase_buffer()
+        if contents or empty_goto:
+            lisp.insert(contents)
+            for mode in modes:
+                lisp[mode + '-mode']()
+            lisp.buffer_disable_undo(new_buffer)
+            lisp.toggle_read_only(1)
+            if switch:
+                if window == 'current':
+                    lisp.switch_to_buffer(new_buffer)
+                else:
+                    lisp.switch_to_buffer_other_window(new_buffer)
+                lisp.goto_char(lisp.point_min())
+            elif window == 'other':
+                new_window = lisp.display_buffer(new_buffer)
+                lisp.set_window_point(new_window, lisp.point_min())
+                if fit_lines and lisp.fboundp(lisp['fit-window-to-buffer']):
+                    lisp.fit_window_to_buffer(new_window, fit_lines)
+                    lisp.bury_buffer(new_buffer)
+        return new_buffer
+
+
+    def hide_buffer(self, name, delete=True):
+        buffer = lisp.get_buffer(name)
+        if buffer is not None:
+            window = lisp.get_buffer_window(buffer)
+            if window is not None:
+                lisp.bury_buffer(buffer)
+                if delete:
+                    lisp.delete_window(window)
+                else:
+                    if lisp.buffer_name(lisp.current_buffer()) == name:
+                        lisp.switch_to_buffer(None)
+
+
+    def message(self, message):
+        lisp.message(message)
+
+
+    def askdata(self, data, starting=None):
+        """`data` is a `ropecommon.dialog.Data` object"""
+        ask_func = self.ask
+        ask_args = {'prompt': data.prompt, 'starting': starting,
+                    'default': data.default}
+        if data.values:
+            ask_func = self.ask_values
+            ask_args['values'] = data.values
+        elif data.kind == 'directory':
+            ask_func = self.ask_directory
+        return ask_func(**ask_args)
+
+
+    def ask_values(self, prompt, values, default=None, starting=None, exact=True):
+        if self._emacs_version() < 22:
+            values = [[value, value] for value in values]
+        if exact and default is not None:
+            prompt = prompt + ('[%s] ' % default)
+        reader = lisp['ropemacs-completing-read-function'].value()
+        result = reader(prompt, values, None, exact, starting)
+        if result == '' and exact:
+            return default
+        return result
+
+
+    def ask(self, prompt, default=None, starting=None):
+        if default is not None:
+            prompt = prompt + ('[%s] ' % default)
+        result = lisp.read_from_minibuffer(prompt, starting, None, None,
+                                           None, default, None)
+        if result == '' and default is not None:
+            return default
+        return result
+
+    def ask_directory(self, prompt, default=None, starting=None):
+        if default is not None:
+            prompt = prompt + ('[%s] ' % default)
+        if lisp.fboundp(lisp['read-directory-name']):
+            result = lisp.read_directory_name(prompt, starting, default)
+        else:
+            result = lisp.read_file_name(prompt, starting, default)
+        if result == '' and default is not None:
+            return default
+        return result
+
+    def _emacs_version(self):
+        return int(lisp['emacs-version'].value().split('.')[0])
+
+    def runtask(self, command, name, interrupts=True):
+        return RunTask(command, name, interrupts)()
+
+    def create_progress(self, name):
+        if lisp.fboundp(lisp['make-progress-reporter']):
+            progress = _LispProgress(name)
+        else:
+            progress = _OldProgress(name)
+        return progress
+
+
+class _LispProgress(object):
+
+    def __init__(self, name):
+        self.progress = lisp.make_progress_reporter('%s ... ' % name, 0, 100)
+
+    def update(self, percent):
+        lisp.progress_reporter_update(self.progress, percent)
+
+    def done(self):
+        lisp.progress_reporter_done(self.progress)
+
+class _OldProgress(object):
+
+    def __init__(self, name):
+        self.name = name
+        self.update(0)
+
+    def update(self, percent):
+        if percent != 0:
+            message('%s ... %s%%%%' % (self.name, percent))
+        else:
+            message('%s ... ' % self.name)
+
+    def done(self):
+        message('%s ... done' % self.name)
+
+
+class RunTask(object):
+
+    def __init__(self, task, name, interrupts=True):
+        self.task = task
+        self.name = name
+        self.interrupts = interrupts
+
+    def __call__(self):
+        handle = taskhandle.TaskHandle(name=self.name)
+        progress = LispUtils().create_progress(self.name)
+        def update_progress():
+            jobset = handle.current_jobset()
+            if jobset:
+                percent = jobset.get_percent_done()
+                if percent is not None:
+                    progress.update(percent)
+        handle.add_observer(update_progress)
+        result = self.task(handle)
+        progress.done()
+        return result
 
 
 def _register_functions(interface):
             globals()[attrname] = attr
 
 
-_interface = ropecommon.interface.Ropemacs()
+_interface = ropecommon.interface.Ropemacs(env=LispUtils())
 _register_functions(_interface)
 _interface.init()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.