Ranjith Ramachandra
Ranjith Ramachandra

Reputation: 10764

Is there any way to fix PEP-8 issues with pydev?

I want to know if there is any way to fix all the PEP-8 issues automatically with a keyboard shortcut in eclipse-pydev. Googling did not get me anywhere.

Since Pydev can detect the PEP-8 issues, should it not be possible to fix them automatically?

Upvotes: 5

Views: 6690

Answers (2)

Fabio Zadrozny
Fabio Zadrozny

Reputation: 25332

You can manually activate the PyDev code-formatter with Ctrl+Shift+F (preferences at: Window > Preferences > PyDev > Editor > Code Style > Code Formatter -- note that you can configure it to run automatically under Window > Preferences > PyDev > Editor > Save Actions).

Note that the internal PyDev code-formatter is pretty conservative and won't do all transformations required for 100% compatible PEP8 code (although it handles the more common cases), so, if it's not enough for your needs, you have some options:

  1. You can use autopep8.py or black which are also integrated into PyDev by default in the latest version (Enabled via Window > Preferences > PyDev > Editor > Code Style > Code Formatter > Formatter Style? and then select autopep8 or black).

  2. You can take a look at PythonTidy (external tool)... it's possible to use it as defined in: http://bear330.wordpress.com/2007/10/30/using-pythontidy-in-pydev-as-code-formatter/

Upvotes: 15

user2549818
user2549818

Reputation: 239

I have made a script make it possible to use autopep8 in pydev as code formatter, and it can be customized to satisfy the coding standard in your team.

If you want to use it, save this code somewhere as pyedit_autopep8.py (pyedit_XXXX.py is required). You also have to install the python packages pep8 and autopep8.

Next, go to eclipse pydev preferences page (at: window > preferences > pydev > scripting pydev) to specify the script location:

Now, in order to invoke autopep8 you can simply press Ctrl+Shift+F while editing python code in eclipse. Format selected text is also supported!

"""
By Per A. Brodtkorb
based on pyedit_pythontidy.py by Bear Huang (http://bear330.wordpress.com/).

This code is public domain.
"""

import tempfile
import os

if False:
    from org.python.pydev.editor import PyEdit  # @UnresolvedImport
    cmd = 'command string'
    editor = PyEdit

assert cmd is not None
assert editor is not None

if cmd == 'onCreateActions':
    from org.python.pydev.editor.actions import PyAction
    from org.python.pydev.core.docutils import PySelection
    from java.lang import Runnable
    from org.eclipse.swt.widgets import Display
    from java.io import FileWriter
    import java.lang.Exception

    FORMAT_ACTION_DEFINITION_ID = "org.python.pydev.editor.actions.pyFormatStd"
    FORMAT_ACTION_ID = "org.python.pydev.editor.actions.navigation.pyFormatStd"

    class Autopep8Action(PyAction):
        def _autopep8(self, text):
            tmp_full_file_name = tempfile.mktemp()
            f1 = FileWriter(tmp_full_file_name)
            f1.write(text)
            f1.close()
            os.system('autopep8-script.py -i "%s"' % (tmp_full_file_name))
            f2 = open(tmp_full_file_name, "r")
            tidy_text = f2.read()
            f2.close()
            os.remove(tmp_full_file_name)
            return tidy_text

        def _get_text(self, selection):
            text = selection.getSelectedText()
            format_all = len(text) == 0
            if format_all:
                print "Autopep8: format all."
                text = selection.getDoc().get()
                text_offset = 0
            else:
                print "Autopep8: Format selected."
                text_offset = selection.getAbsoluteCursorOffset()
            return text, text_offset

        def run(self):
            try:
                selection = PySelection(editor)

                text, text_offset = self._get_text(selection)
                tidy_text = self._autopep8(text)

                if len(text)==len(tidy_text):
                    print "Autopep8: Nothing todo!"
                else:
                    doc = selection.getDoc()
                    doc.replace(text_offset, len(text), tidy_text)

            except java.lang.Exception, e:
                self.beep(e)

    def bindInInterface():
        act = Autopep8Action()
        act.setActionDefinitionId(FORMAT_ACTION_DEFINITION_ID)
        act.setId(FORMAT_ACTION_ID)
        try:
            editor.setAction(FORMAT_ACTION_ID, act)
        except:
            pass

    class RunInUi(Runnable):

        '''Helper class that implements a Runnable (just so that we
        can pass it to the Java side). It simply calls some callable.
        '''

        def __init__(self, c):
            self.callable = c

        def run(self):
            self.callable()

    def runInUi(callable):
        '''
        @param callable: the callable that will be run in the UI
        '''
        Display.getDefault().asyncExec(RunInUi(callable))

    runInUi(bindInInterface)

Upvotes: 4

Related Questions