예제 #1
0
def main():
    readme_path = 'README.rst'
    before_key = 'Before running autopep8.\n\n.. code-block:: python'
    after_key = 'After running autopep8.\n\n.. code-block:: python'

    (top, before, bottom) = split_readme(readme_path,
                                         before_key=before_key,
                                         after_key=after_key,
                                         end_key='Options::')

    input_code = textwrap.dedent(before)

    output_code = autopep8.fix_string(
        input_code,
        options=autopep8.parse_args(['', '--aggressive'])[0])
    compile(output_code, '<string>', 'exec', dont_inherit=True)

    new_readme = '\n\n'.join([
        top,
        before_key, before,
        after_key, indent(output_code),
        bottom])

    with open(readme_path, 'w') as output_file:
        output_file.write(new_readme)
예제 #2
0
    def itercode(self):
        """Returns a generator like [(relative_path of directory, code_string)...]"""
        for relative_path, codes in self._codes.iteritems():
            code = '\n\n'.join([ c.render() for c in codes ])

            if relative_path.endswith('.py'):
                try:
                    try:
                        # get the base imports
                        imports = codes[0].namespace.imports().items() # tuples (import symbol, identifier to use)
                    except AttributeError:
                        imports = []

                    import_codes = []
                    for import_symbol, identifier in imports:
                        if isinstance(import_symbol, basestring) and import_symbol.startswith('django.'):
                            import_string = IMPORTS[import_symbol]
                            m = re.match(r'from (.*) import (.*)$', import_string)
                            from_string, real_import_name = (m.group(1), m.group(2))
                        elif import_symbol[0].startswith('webapp.'):
                            from_string, real_import_name = import_symbol[0], import_symbol[1]
                        elif import_symbol.startswith('utils.'):
                            # The case where you want to import third party applications/non webapp or django modules
                            import_string = IMPORTS[import_symbol]
                            m = re.match(r'from (.*) import (.*)$', import_string)
                            from_string, real_import_name = (m.group(1), m.group(2))
                        else:
                            print import_symbol
                            raise KeyError
                        i = Import(real_import_name, identifier, from_string=from_string)
                        import_codes.append(i)

                    # looks complicated, but it's just collecting the imports by same from_string,
                    # using sorted to ensure determinism of outputted code, for fast deploy to work.
                    imports_by_from_string = { fs: [i for i in import_codes if i.from_string == fs] for fs in sorted(set([i.from_string for i in import_codes]))}
                    normal_imports = '\n'.join([i.render() for i in sorted(imports_by_from_string.get('',[]))])
                    try:
                        del imports_by_from_string['']
                    except KeyError:
                        pass
                    from_string_imports = '\n'.join(sorted([Import.render_concatted_imports(imps) for imps in imports_by_from_string.values()]))

                    code = normal_imports + '\n\n' + from_string_imports + '\n\n' + code
                    try:
                        compile(code + "\n", relative_path, "exec")
                    except IndentationError:
                        traceback.print_exc()
                        print code
                        continue

                except SyntaxError:
                    traceback.print_exc()
                    print code
                    continue
                else:
                    code = autopep8.fix_string(code)

            yield (relative_path, code)
 def _open_with_pep8(self):
     exts = settings.SYNTAX.get('python')['extension']
     file_ext = file_manager.get_file_extension(
         self.editor_s.get_editor_path())
     if file_ext in exts:
         editorWidget = self.editor_s.get_editor()
         if editorWidget:
             source = self.editor_s.get_text()
             fixed_source = autopep8.fix_string(source)
             self.editor_s.add_editor("", fixed_source, "py")
 def _open_with_pep8(self):
     exts = settings.SYNTAX.get('python')['extension']
     file_ext = file_manager.get_file_extension(
         self.editor_s.get_editor_path())
     if file_ext in exts:
         editorWidget = self.editor_s.get_editor()
         if editorWidget:
             source = self.editor_s.get_text()
             fixed_source = autopep8.fix_string(source)
             self.editor_s.add_editor("", fixed_source, "py")
예제 #5
0
    def post(self):
        result = {}
        body = self.request.get('body')

        try:
            result['Body'] = autopep8.fix_string(body)
        except Exception as e:
            result['Error'] = str(e)

        self.response.headers['Content-Type'] = 'application/json'
        self.response.write(json.dumps(result))
    def _rewrite_pep8(self):
        editorWidget = self.editor_s.get_editor()
        if editorWidget:
            last_cursor_pos = editorWidget.get_cursor_position()

            source = self.editor_s.get_text()
            fixed_source = autopep8.fix_string(source)
            editorWidget.selectAll()
            editorWidget.textCursor().insertText(fixed_source)

            editorWidget.set_cursor_position(last_cursor_pos)
예제 #7
0
 def run(self, edit):
     syntax = self.view.settings().get('syntax')
     if syntax.lower().find('python') == -1:
         return
     replace_region = self.view.line(sublime.Region(0, self.view.size()))
     source = self.view.substr(replace_region)
     fixed = autopep8.fix_string(source, options=PPA.get_options())
     is_dirty, err = MergeUtils.merge_code(self.view, edit, source, fixed)
     if err:
         sublime.error_message("%s: Merge failure: '%s'" %
                               (PLUGIN_NAME, err))
         raise
예제 #8
0
 def run(self, edit):
     syntax = self.view.settings().get('syntax')
     if syntax.lower().find('python') == -1:
         return
     replace_region = self.view.line(
         sublime.Region(0, self.view.size()))
     source = self.view.substr(replace_region)
     fixed = autopep8.fix_string(source, options=PPA.get_options())
     is_dirty, err = MergeUtils.merge_code(
         self.view, edit, source, fixed)
     if err:
         sublime.error_message(
             "%s: Merge failure: '%s'" % (PLUGIN_NAME, err))
         raise
    def _rewrite_pep8(self):
        exts = settings.SYNTAX.get('python')['extension']
        file_ext = file_manager.get_file_extension(
            self.editor_s.get_editor_path())
        if file_ext in exts:
            editorWidget = self.editor_s.get_editor()
            if editorWidget:
                last_cursor_pos = editorWidget.get_cursor_position()

                source = self.editor_s.get_text()
                fixed_source = autopep8.fix_string(source)
                editorWidget.selectAll()
                editorWidget.textCursor().insertText(fixed_source)

                editorWidget.set_cursor_position(last_cursor_pos)
    def _rewrite_pep8(self):
        exts = settings.SYNTAX.get('python')['extension']
        file_ext = file_manager.get_file_extension(
            self.editor_s.get_editor_path())
        if file_ext in exts:
            editorWidget = self.editor_s.get_editor()
            if editorWidget:
                last_cursor_pos = editorWidget.get_cursor_position()

                source = self.editor_s.get_text()
                fixed_source = autopep8.fix_string(source)
                editorWidget.selectAll()
                editorWidget.textCursor().insertText(fixed_source)

                editorWidget.set_cursor_position(last_cursor_pos)
    def run(self, edit):
        replace_region = self.view.line(sublime.Region(0L, self.view.size()))
        source = self.view.substr(replace_region)
        options = autopep8.parse_args([''])[0]
        if IGNORE:
            options.ignore = IGNORE
        if SELECT:
            options.select = SELECT
        if MAX_LINE_LENGTH:
            options.max_line_length = MAX_LINE_LENGTH
        if AGGRESSIVE:
            options.aggressive = True

        fixed = autopep8.fix_string(source, options=options)
        is_dirty, err = MergeUtils.merge_code(self.view, edit, source, fixed)
        if err:
            sublime.error_message("%s: Merge failure: '%s'" % (PLUGIN_NAME, err))
예제 #12
0
def main():
    README_PATH = 'README.rst'
    BEFORE_KEY = 'Before running autopep8.\n\n.. code-block:: python'
    AFTER_KEY = 'After running autopep8.\n\n.. code-block:: python'

    (top, before, bottom) = split_readme(README_PATH,
                                         before_key=BEFORE_KEY,
                                         after_key=AFTER_KEY,
                                         end_key='Options::')

    import textwrap
    new_readme = '\n\n'.join([
        top,
        BEFORE_KEY, before,
        AFTER_KEY, indent(autopep8.fix_string(textwrap.dedent(before))),
        bottom])

    with open(README_PATH, 'w') as output_file:
        output_file.write(new_readme)
예제 #13
0
def main():
    readme_path = 'README.rst'
    before_key = 'Before running autopep8.\n\n.. code-block:: python'
    after_key = 'After running autopep8.\n\n.. code-block:: python'

    (top, before, bottom) = split_readme(readme_path,
                                         before_key=before_key,
                                         after_key=after_key,
                                         end_key='Options::')

    import textwrap
    new_readme = '\n\n'.join([
        top,
        before_key, before,
        after_key, indent(autopep8.fix_string(
            textwrap.dedent(before),
            options=autopep8.parse_args(['', '--aggressive'])[0])),
        bottom])

    with open(readme_path, 'w') as output_file:
        output_file.write(new_readme)
예제 #14
0
    def run_autopep8(self):
        """Format code with autopep8"""
        if ERR_MSG:
            self.main.statusBar().showMessage(
                _("Unable to run: {0}".format(ERR_MSG)))
            return

        # Retrieve active fixes
        ignore = []
        for code, description in FIX_LIST:
            if not self.get_option(code, True):
                ignore.append(code)

        # Retrieve text of current opened file
        editorstack = self.main.editor.get_current_editorstack()
        index = editorstack.get_stack_index()
        finfo = editorstack.data[index]
        editor = finfo.editor
        cursor = editor.textCursor()
        cursor.beginEditBlock()  # Start cancel block
        if not cursor.hasSelection():
            position_start = 0
            cursor.select(QTextCursor.Document)  # Select all
        else:
            # Select whole lines
            position_end = cursor.selectionEnd()
            cursor.setPosition(cursor.selectionStart())
            cursor.movePosition(QTextCursor.StartOfLine)
            position_start = cursor.position()
            cursor.setPosition(position_end, QTextCursor.KeepAnchor)
            cursor.movePosition(QTextCursor.StartOfLine,
                                QTextCursor.KeepAnchor)
            position_lastline_start = cursor.position()
            if not position_end == position_lastline_start:
                cursor.movePosition(QTextCursor.EndOfLine,
                                    QTextCursor.KeepAnchor)
                # Select EOL if not on a new line
                if not position_lastline_start == cursor.position():
                    cursor.movePosition(QTextCursor.Right,
                                        QTextCursor.KeepAnchor)

            # Disable checks of newlines at end of file
            if not cursor.atEnd():
                ignore.append("W391")

        # replace(): See qt doc for QTextCursor.selectedText()
        text_before = to_text_string(cursor.selectedText().replace(
            "\u2029", "\n"))

        # Run autopep8
        options = [
            "", "--ignore", ",".join(ignore), "--pep8-passes",
            str(self.get_option("passes", 0) - 1), "--max-line-length",
            str(self.main.window().editor.get_option("edge_line_column"))
        ]
        if self.get_option("aggressive1", False):
            options.append("--aggressive")
            if self.get_option("aggressive2", False):
                options.append("--aggressive")
        options = autopep8.parse_args(options)[0]
        text_after = autopep8.fix_string(text_before, options)

        # Apply new text if needed
        if text_before != text_after:
            cursor.insertText(text_after)  # Change text

        cursor.endEditBlock()  # End cancel block

        # Select changed text
        position_end = cursor.position()
        cursor.setPosition(position_start, QTextCursor.MoveAnchor)
        cursor.setPosition(position_end, QTextCursor.KeepAnchor)
        editor.setTextCursor(cursor)

        self.main.statusBar().showMessage(_("Autopep8 finished !"))
예제 #15
0
    def itercode(self):
        """Returns a generator like [(relative_path of directory, code_string)...]"""
        for relative_path, codes in self._codes.iteritems():
            code = '\n\n'.join([c.render() for c in codes])

            if relative_path.endswith('.py'):
                try:
                    try:
                        # get the base imports
                        imports = codes[0].namespace.imports().items(
                        )  # tuples (import symbol, identifier to use)
                    except AttributeError:
                        imports = []

                    import_codes = []
                    for import_symbol, identifier in imports:
                        if isinstance(import_symbol,
                                      basestring) and import_symbol.startswith(
                                          'django.'):
                            import_string = IMPORTS[import_symbol]
                            m = re.match(r'from (.*) import (.*)$',
                                         import_string)
                            from_string, real_import_name = (m.group(1),
                                                             m.group(2))
                        elif import_symbol[0].startswith('webapp.'):
                            from_string, real_import_name = import_symbol[
                                0], import_symbol[1]
                        elif import_symbol.startswith('utils.'):
                            # The case where you want to import third party applications/non webapp or django modules
                            import_string = IMPORTS[import_symbol]
                            m = re.match(r'from (.*) import (.*)$',
                                         import_string)
                            from_string, real_import_name = (m.group(1),
                                                             m.group(2))
                        else:
                            print import_symbol
                            raise KeyError
                        i = Import(real_import_name,
                                   identifier,
                                   from_string=from_string)
                        import_codes.append(i)

                    # looks complicated, but it's just collecting the imports by same from_string,
                    # using sorted to ensure determinism of outputted code, for fast deploy to work.
                    imports_by_from_string = {
                        fs: [i for i in import_codes if i.from_string == fs]
                        for fs in sorted(
                            set([i.from_string for i in import_codes]))
                    }
                    normal_imports = '\n'.join([
                        i.render()
                        for i in sorted(imports_by_from_string.get('', []))
                    ])
                    try:
                        del imports_by_from_string['']
                    except KeyError:
                        pass
                    from_string_imports = '\n'.join(
                        sorted([
                            Import.render_concatted_imports(imps)
                            for imps in imports_by_from_string.values()
                        ]))

                    code = normal_imports + '\n\n' + from_string_imports + '\n\n' + code
                    try:
                        compile(code + "\n", relative_path, "exec")
                    except IndentationError:
                        traceback.print_exc()
                        print code
                        continue

                except SyntaxError:
                    traceback.print_exc()
                    print code
                    continue
                else:
                    code = autopep8.fix_string(code)

            yield (relative_path, code)
예제 #16
0
    def run_autopep8(self):
        """Format code with autopep8"""
        if ERR_MSG:
            self.main.statusBar().showMessage(
                _("Unable to run: {0}".format(ERR_MSG)))
            return

        # Retrieve active fixes
        ignore = []
        for code, description in FIX_LIST:
            if not self.get_option(code, True):
                ignore.append(code)

        # Retrieve text of current opened file
        editorstack = self.main.editor.get_current_editorstack()
        index = editorstack.get_stack_index()
        finfo = editorstack.data[index]
        editor = finfo.editor
        cursor = editor.textCursor()
        cursor.beginEditBlock()  # Start cancel block
        if not cursor.hasSelection():
            position_start = 0
            cursor.select(QTextCursor.Document)  # Select all
        else:
            # Select whole lines
            position_end = cursor.selectionEnd()
            cursor.setPosition(cursor.selectionStart())
            cursor.movePosition(QTextCursor.StartOfLine)
            position_start = cursor.position()
            cursor.setPosition(position_end, QTextCursor.KeepAnchor)
            cursor.movePosition(QTextCursor.StartOfLine,
                                QTextCursor.KeepAnchor)
            position_lastline_start = cursor.position()
            if not position_end == position_lastline_start:
                cursor.movePosition(QTextCursor.EndOfLine,
                                    QTextCursor.KeepAnchor)
                # Select EOL if not on a new line
                if not position_lastline_start == cursor.position():
                    cursor.movePosition(QTextCursor.Right,
                                        QTextCursor.KeepAnchor)

            # Disable checks of newlines at end of file
            if not cursor.atEnd():
                ignore.append("W391")

        # replace(): See qt doc for QTextCursor.selectedText()
        text_before = to_text_string(
            cursor.selectedText().replace("\u2029", "\n"))

        # Run autopep8
        options = ["", "--ignore", ",".join(ignore),
                   "--pep8-passes", str(self.get_option("passes", 0) - 1),
                   "--max-line-length",
                   str(self.main.window().editor.get_option("edge_line_column"))]
        if self.get_option("aggressive1", False):
            options.append("--aggressive")
            if self.get_option("aggressive2", False):
                options.append("--aggressive")
        options = autopep8.parse_args(options)[0]
        text_after = autopep8.fix_string(text_before, options)

        # Apply new text if needed
        if text_before != text_after:
            cursor.insertText(text_after)  # Change text

        cursor.endEditBlock()  # End cancel block

        # Select changed text
        position_end = cursor.position()
        cursor.setPosition(position_start, QTextCursor.MoveAnchor)
        cursor.setPosition(position_end, QTextCursor.KeepAnchor)
        editor.setTextCursor(cursor)

        self.main.statusBar().showMessage(
            _("Autopep8 finished !"))
예제 #17
0
"""Run autopep8 on the selected buffer in Vim.

map <C-I> :pyfile <path_to>/autopep8_vim.py<CR>

"""

import vim
if vim.eval('&syntax') == 'python':
    encoding = vim.eval('&fileencoding')
    source = '\n'.join(line.decode(encoding)
                       for line in vim.current.buffer) + '\n'

    import autopep8
    options = autopep8.parse_args(['--range',
                                   str(1 + vim.current.range.start),
                                   str(1 + vim.current.range.end),
                                   ''])[0]

    formatted = autopep8.fix_string(source, options=options)

    if source != formatted:
        if formatted.endswith('\n'):
            formatted = formatted[:-1]

        vim.current.buffer[:] = [line.encode(encoding)
                                 for line in formatted.splitlines()]
 def _open_with_pep8(self):
     editorWidget = self.editor_s.get_editor()
     if editorWidget:
         source = self.editor_s.get_text()
         fixed_source = autopep8.fix_string(source)
         self.editor_s.add_editor("", fixed_source, "py")