Skip to content

Instantly share code, notes, and snippets.

@KubaO
Last active September 9, 2024 13:21
Show Gist options
  • Save KubaO/2e344c1ec86b4693fe19173390960822 to your computer and use it in GitHub Desktop.
Save KubaO/2e344c1ec86b4693fe19173390960822 to your computer and use it in GitHub Desktop.
A bare-bone Thonny AutoPep8 extension.
import autopep8
from thonny import get_workbench
from tkinter.messagebox import showinfo
DEBUG = False
# Save to:
# %APPDATA%\Roaming\Thonny\plugins\Python3.10\site-packages\thonnycontrib\autopep8.py
# references:
# https://bitbucket.org/aivarannamaa/tktextext/src/master/tktextext.py
# https://github.com/hhatto/autopep8?tab=readme-ov-file#use-as-a-module
# https://github.com/thonny/thonny/blob/master/thonny/editors.py
# https://github.com/thonny/thonny/blob/master/thonny/codeview.py
# https://github.com/thonny/thonny/blob/master/thonny/plugins/cells.py
def run_autopep8_on_code():
workbench = get_workbench()
editor = workbench.get_editor_notebook().get_current_editor()
# thonny.CodeView
view = editor.get_code_view()
# thonny.CodeViewText, tktextext.EnhancedText, thonny.SyntaxText,
cvtext = editor.get_text_widget()
curpos = list(cvtext.get_cursor_position()) # [line, col]
if DEBUG:
filename = editor.get_filename()
msg = f"workbench={str(workbench)} editor={str(editor)} file={str(filename)}\nclass={editor.__class__.__name__}" \
f"\ncursor_position={curpos}"
showinfo(title="Debug", message=msg)
# text = cvtext.get("1.0", "end")
# msg="text={text}"
# showinfo(title="Pos", message=msg)
# tktextext.TweakableText
# widget.set_content("something")
code = view.get_content()
fixed_code = autopep8.fix_code(code, options={'aggressive': 2})
if code != fixed_code:
view.set_content(fixed_code, keep_undo=True)
editor.select_line(*curpos)
# cvtext.tag_remove("sel", "1.0", 'end') # tk.END='end'
view._clean_selection()
def load_plugin():
get_workbench().add_command(command_id="autopep8",
menu_name="tools",
command_label="AutoPep8",
handler=run_autopep8_on_code,
default_sequence="<Control-Shift-KeyPress-F>"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment