Skip to content

Added smart indentation for python. #38

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion example.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def __init__(self):

contents = Path(__file__).read_text()

self.editor = SyntaxEdit(contents, syntax="Python")
self.editor = SyntaxEdit(contents, syntax="Python", use_smart_indentation=True)
self.editor.textChanged.connect(self.editor_changed)

style_language = QHBoxLayout()
Expand Down
31 changes: 31 additions & 0 deletions syntaxedit/core.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from qtpy import QtGui
from qtpy.QtGui import QTextCursor
from qtpy.QtCore import Qt
from qtpy.QtWidgets import QTextEdit

from pygments.styles import get_style_by_name
Expand All @@ -18,10 +20,12 @@ def __init__(
theme="solarized-light",
indentation_size=4,
use_theme_background=True,
use_smart_indentation=True,
):
super().__init__("", parent)

self._indentation_size = indentation_size
self._use_smart_indentation = use_smart_indentation

self._font = font
self._font_size = font_size
Expand Down Expand Up @@ -92,3 +96,30 @@ def setCursorPosition(self, position):

def setContents(self, contents):
self.setPlainText(contents)


def keyPressEvent(self, event):
if self._use_smart_indentation and event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
cursor = self.textCursor()
cursor.movePosition(QTextCursor.StartOfLine, QTextCursor.KeepAnchor)
current_line_text = cursor.selectedText()

# indentation may be tabs or spaces, get the leading whitespace
indent = ""
for char in current_line_text:
if char == " " or char == "\t":
indent += char
else:
break

# if the previous line ended with a colon, indent the new line by one level
if current_line_text.strip().endswith(":"):
if '\t' in indent:
indent += '\t'
else:
indent += " " * self._indentation_size

super().keyPressEvent(event)
self.insertPlainText(indent)
else:
super().keyPressEvent(event)