Skip to content

Instantly share code, notes, and snippets.

@ssokolow
Last active July 22, 2022 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssokolow/abb20a30415fa4debce912c38060ca6a to your computer and use it in GitHub Desktop.
Save ssokolow/abb20a30415fa4debce912c38060ca6a to your computer and use it in GitHub Desktop.
QLineEdit replacement with automatic PyEnchant spell-checking (based on QPlainTextEdit because it's easier to implement)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Single-Line QPlainTextEdit With Inline Spell Check mimicking QLineEdit
Original PyQt4 Version:
https://nachtimwald.com/2009/08/22/qplaintextedit-with-in-line-spell-check/
Multi-Line Version:
https://gist.github.com/ssokolow/0e69b9bd9ca442163164c8a9756aa15f
TODO:
- Go through the change history and write tests for all of the issues I fixed.
Copyright 2009 John Schember
Copyright 2018-2022 Stephan Sokolow
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
__license__ = 'MIT'
__author__ = 'John Schember; Stephan Sokolow'
__docformat__ = 'restructuredtext en'
import sys
from typing import Dict, List, Optional, Tuple
# pylint: disable=invalid-sequence-index,unsubscriptable-object
import enchant # type: ignore
from enchant import tokenize
from enchant.errors import TokenizerNotFoundError # type: ignore
from enchant.utils import trim_suggestions # type: ignore
# pylint: disable=no-name-in-module
from PyQt5.QtCore import (Qt, QCoreApplication, QPoint, QSize,
pyqtSignal, pyqtSlot)
from PyQt5.QtGui import (QContextMenuEvent, QFocusEvent, QFontMetricsF,
QIcon, QKeySequence, QSyntaxHighlighter, QTextBlockUserData, QTextOption,
QTextCharFormat, QTextCursor)
from PyQt5.QtWidgets import (QAction, QActionGroup, QApplication, QLineEdit,
QMenu, QPlainTextEdit, QShortcut, QSizePolicy, QStyle, QStyleOptionFrame,
QVBoxLayout, QWidget)
CHUNKERS: Dict[str, Tuple[str, List[tokenize.Chunker]]] = {
# Rely on dicts having guaranteed ordering as of Python 3.7
'text': (QCoreApplication.translate("OneLineSpellTextEdit",
'Text', "Context Menu's Format Submenu"), []),
'html': (QCoreApplication.translate("OneLineSpellTextEdit",
'HTML', "Context Menu's Format Submenu"), [tokenize.HTMLChunker])
}
class OneLineSpellTextEdit(QPlainTextEdit):
"""QPlainTextEdit subclass which does spell-checking using PyEnchant
and mimics QLineEdit to work around QLineEdit being more difficult to
hook spell-checking into"""
# Clamping value for words like "regex" which suggest so many things that
# the menu runs from the top to the bottom of the screen and spills over
# into a second column.
max_suggestions = 20
# Alias this here so it can be overridden without modifying the "constant"
format_choices = CHUNKERS
_format = 'text'
# Expose all changes I want to be able to persist across restarts
#
# OneLineSpellTextEdit::document()::contentsChanged
format_changed = pyqtSignal(str)
lang_changed = pyqtSignal(str)
overtype_changed = pyqtSignal(bool)
# Provide an event to allow additions to the context menu
aboutToShowContextMenu = pyqtSignal(QMenu)
def __init__(self, *args):
QPlainTextEdit.__init__(self, *args)
# Start with a default dictionary based on the current locale.
self.highlighter = EnchantHighlighter(self.document())
# Set up expected Insert/Overwrite cursor mode toggle
QShortcut(
QKeySequence(
self.tr("Insert", "Hotkey to toggle Insert/Overwrite")),
self, self.cb_toggle_insert, context=Qt.WidgetShortcut)
# Set up QPlainTextEdit to act like QLineEdit
self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
self.setLineWrapMode(QPlainTextEdit.NoWrap)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setWordWrapMode(QTextOption.NoWrap)
self.setTabChangesFocus(True)
self.textChanged.connect(self.cb_text_changed)
def augmentEditMenu(self, menu: QMenu):
"""Add elements common to the context and Edit menus"""
menu.addSeparator()
menu.addMenu(self.createLanguagesMenu(menu))
menu.addMenu(self.createFormatsMenu(menu))
def contextMenuEvent(self, event: QContextMenuEvent):
"""Custom context menu handler to add a spelling suggestions submenu"""
popup_menu = self.createSpellcheckContextMenu(event.pos())
popup_menu.exec_(event.globalPos())
def createSpellcheckContextMenu(self, pos: QPoint) -> QMenu:
"""Create and return an augmented default context menu."""
menu = self.createStandardContextMenu(pos)
# Add a submenu for setting the spell-check language
self.augmentEditMenu(menu)
# Try to retrieve a menu of corrections for the right-clicked word
spell_menu = self.createCorrectionsMenu(
self.cursorForMisspelling(pos), menu)
if spell_menu:
menu.insertSeparator(menu.actions()[0])
menu.insertMenu(menu.actions()[0], spell_menu)
# Allow the parent application to alter the menu
self.aboutToShowContextMenu.emit(menu)
return menu
def createCorrectionsMenu(self, cursor: Optional[QTextCursor],
parent: QWidget = None) -> Optional[QMenu]:
"""Create and return a menu for correcting the selected word."""
if not cursor:
return None
text = cursor.selectedText()
if not text:
return None # Prevent ValueError from enchant
suggests = trim_suggestions(text,
self.highlighter.dict().suggest(text),
self.max_suggestions)
spell_menu = QMenu(
self.tr('Spelling Suggestions', "Submenu Name for Context Menu"),
parent)
for word in suggests:
action = QAction(word, spell_menu)
action.setData((cursor, word))
spell_menu.addAction(action)
# Only return the menu if it's non-empty
if spell_menu.actions():
spell_menu.triggered.connect(self._cb_correct_word)
return spell_menu
return None
def createLanguagesMenu(self, parent: QWidget = None) -> QMenu:
"""Create and return a menu for selecting the spell-check language."""
curr_lang = self.highlighter.dict().tag
lang_menu = QMenu(self.tr("&Language",
"Submenu Name for Context Menu"), parent)
lang_actions = QActionGroup(lang_menu)
for lang in enchant.list_languages():
action = lang_actions.addAction(lang)
action.setCheckable(True)
action.setChecked(lang == curr_lang)
action.setData(lang)
lang_menu.addAction(action)
lang_menu.triggered.connect(self._cb_set_language)
lang_menu.setIcon(QIcon.fromTheme("set-language"))
return lang_menu
def createFormatsMenu(self, parent: QWidget = None) -> QMenu:
"""Create and return a menu for selecting the spell-check language."""
fmt_menu = QMenu(self.tr("&Format",
"Submenu Name for Context Menu"), parent)
fmt_actions = QActionGroup(fmt_menu)
curr_format = self.highlighter.chunkers()
for fmt_id, (name, chunkers) in self.format_choices.items():
action = fmt_actions.addAction(name)
action.setCheckable(True)
action.setChecked(chunkers == curr_format)
action.setData(fmt_id)
fmt_menu.addAction(action)
fmt_menu.triggered.connect(self._cb_set_format)
fmt_menu.setIcon(QIcon.fromTheme("format-text-code"))
return fmt_menu
def cursorForMisspelling(self, pos: QPoint) -> Optional[QTextCursor]:
"""Return a cursor selecting the misspelled word at ``pos`` or ``None``
This leverages the fact that QPlainTextEdit already has a system for
processing its contents in limited-size blocks to keep things fast.
"""
cursor = self.cursorForPosition(pos)
misspelled_words = getattr(cursor.block().userData(), 'misspelled', [])
# If the cursor is within a misspelling, select the word
for (start, end) in misspelled_words:
if start <= cursor.positionInBlock() <= end:
block_pos = cursor.block().position()
cursor.setPosition(block_pos + start, QTextCursor.MoveAnchor)
cursor.setPosition(block_pos + end, QTextCursor.KeepAnchor)
break
if cursor.hasSelection(): # pylint: disable=no-else-return
return cursor
else:
return None
def focusInEvent(self, e: QFocusEvent):
"""Override focusInEvent to mimic QLineEdit behaviour"""
super(OneLineSpellTextEdit, self).focusInEvent(e)
# TODO: Are there any other things I'm supposed to be checking for?
if e.reason() in (Qt.BacktabFocusReason, Qt.ShortcutFocusReason,
Qt.TabFocusReason):
self.selectAll()
def focusOutEvent(self, e: QFocusEvent):
"""Override focusOutEvent to mimic QLineEdit behaviour"""
super(OneLineSpellTextEdit, self).focusOutEvent(e)
# TODO: Are there any other things I'm supposed to be checking for?
if e.reason() in (Qt.BacktabFocusReason, Qt.MouseFocusReason,
Qt.ShortcutFocusReason, Qt.TabFocusReason):
# De-select everything and move the cursor to the end
cur = self.textCursor()
cur.movePosition(QTextCursor.End)
self.setTextCursor(cur)
def format(self):
"""Read-only access to the format ID"""
return self._format
def minimumSizeHint(self):
"""Redefine minimum size hint to match QLineEdit"""
block_fmt = self.document().firstBlock().blockFormat()
width = super(OneLineSpellTextEdit, self).minimumSizeHint().width()
height = int(
QFontMetricsF(self.font()).lineSpacing() + # noqa
block_fmt.topMargin() + block_fmt.bottomMargin() + # noqa
self.document().documentMargin() + # noqa
2 * self.frameWidth()
)
style_opts = QStyleOptionFrame()
style_opts.initFrom(self)
style_opts.lineWidth = self.frameWidth()
# TODO: Is it correct that I'm achieving the correct content height
# under test conditions by feeding self.frameWidth() to both
# QStyleOptionFrame.lineWidth and the sizeFromContents height
# calculation?
return self.style().sizeFromContents(
QStyle.CT_LineEdit,
style_opts,
QSize(width, height),
self
)
@pyqtSlot(str)
def setFormat(self, format_id: str) -> bool:
"""Event handler for 'Format' menu entries."""
if format_id not in self.format_choices:
return False
chunkers = self.format_choices[format_id][1]
self.highlighter.setChunkers(chunkers)
self._format = format_id
self.format_changed.emit(format_id)
return True
def sizeHint(self):
"""Reuse minimumSizeHint for sizeHint"""
return self.minimumSizeHint()
@pyqtSlot(QAction)
def _cb_correct_word(self, action: QAction): # pylint: disable=R0201
"""Event handler for 'Spelling Suggestions' entries."""
cursor, word = action.data()
cursor.beginEditBlock()
cursor.removeSelectedText()
cursor.insertText(word)
cursor.endEditBlock()
@pyqtSlot(QAction)
def _cb_set_format(self, action: QAction):
"""Event handler for 'Format' menu entries."""
fmt_id = action.data()
self.setFormat(fmt_id)
@pyqtSlot(QAction)
def _cb_set_language(self, action: QAction):
"""Event handler for 'Language' menu entries."""
lang = action.data()
self.highlighter.setDict(enchant.Dict(lang))
self.lang_changed.emit(lang)
@pyqtSlot()
def cb_text_changed(self):
"""Handler to enforce one-linedness on typing/pastes/etc.
(Can't use self.setMaximumBlockCount(1) because it disables Undo/Redo)
Feel free to subclass and override this for alternative behaviours
such as converting a newline-separated list into a comma-separated list
"""
if self.document().blockCount() > 1:
self.document().setPlainText(
self.document().firstBlock().text())
@pyqtSlot()
def cb_toggle_insert(self, target: bool = None):
"""Event handler for the Insert key"""
if target is None:
target = not self.overwriteMode()
self.setOverwriteMode(target)
self.overtype_changed.emit(target)
class EnchantHighlighter(QSyntaxHighlighter):
"""QSyntaxHighlighter subclass which consults a PyEnchant dictionary"""
token_filters = (tokenize.EmailFilter, tokenize.URLFilter)
# Define the spellcheck style once and just assign it as necessary
err_format = QTextCharFormat()
err_format.setUnderlineColor(Qt.red)
err_format.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)
def __init__(self, *args):
QSyntaxHighlighter.__init__(self, *args)
# Initialize private members with default dict based on locale,
# configured for plaintext
self._chunkers = []
self.setDict(enchant.Dict())
def chunkers(self) -> List[tokenize.Chunker]:
"""Gets the chunkers in use"""
return self._chunkers
def dict(self) -> enchant.Dict:
"""Gets the spelling dictionary in use"""
return self._sp_dict
def setChunkers(self, chunkers: List[tokenize.Chunker]):
"""Sets the list of chunkers to be used"""
old_dict = self.dict()
old_chunkers = chunkers
self._chunkers = chunkers
try:
self.setDict(old_dict)
except Exception: # pylint: disable=broad-except
self._chunkers = old_chunkers
self.setDict(old_dict)
def setDict(self, sp_dict: enchant.Dict):
"""Sets the spelling dictionary to be used"""
assert sp_dict is not None # nosec
try:
self.tokenizer = tokenize.get_tokenizer(sp_dict.tag,
chunkers=self._chunkers, filters=self.token_filters)
except TokenizerNotFoundError:
# Fall back to the "good for most euro languages" English tokenizer
self.tokenizer = tokenize.get_tokenizer(
chunkers=self._chunkers, filters=self.token_filters)
self._sp_dict = sp_dict
self.rehighlight()
def highlightBlock(self, text: str):
"""Overridden QSyntaxHighlighter method to apply the highlight"""
# TODO: Can I refactor the code to avoid the need for this check?
if not (self._sp_dict and self.tokenizer):
return
# Build a list of all misspelled words and highlight them
misspellings = []
for (word, pos) in self.tokenizer(text):
if not self._sp_dict.check(word):
self.setFormat(pos, len(word), self.err_format)
misspellings.append((pos, pos + len(word)))
# Store the list so the context menu can reuse this tokenization pass
# (Block-relative values so editing other blocks won't invalidate them)
data = QTextBlockUserData()
data.misspelled = misspellings # type: ignore
self.setCurrentBlockUserData(data)
if __name__ == '__main__': # pragma: nocover
app = QApplication(sys.argv)
win = QWidget()
layout = QVBoxLayout()
spellEdit = OneLineSpellTextEdit()
spellEdit.setPlainText("OneLine SpellTextEdit")
le = QLineEdit()
le.setText("QLineEdit")
print(spellEdit.sizeHint(), spellEdit.minimumSizeHint())
print(le.sizeHint(), le.minimumSizeHint())
layout.addWidget(spellEdit)
layout.addWidget(le)
win.setLayout(layout)
win.show()
# pylint: disable=line-too-long
# TODO:
# - Support user-scoped and document-scoped PersonalDict/Ignored lists.
# Dict.add_to_pwl()
# Dict.add_to_session() ("Ignore Word" for just this session)
# Dict.add_to_session() ("Add to document dictionary",
# Will need to be manually persisted)
# Dict.remove()
# Dict.remove_from_session() (Will need to be manually persisted)
# Dict.store_replacement() (For storing "probably correct" hints)
#
# - Consider offering an option to force plaintext copy-to-clipboard for
# things which have buggy support for receiving HTML pastes.
# https://forum.qt.io/topic/33565/prevent-qplaintextedit-from-copying-html-to-clipboard
sys.exit(app.exec_())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment