-
-
Save tritium21/f09ce417edd035fca488fd2b1f7ec2a8 to your computer and use it in GitHub Desktop.
Spell-checked QPlainTextEdit for PyQt 5.x using PyEnchant
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """QPlainTextEdit With Inline Spell Check | |
| Original PyQt4 Version: | |
| https://nachtimwald.com/2009/08/22/qplaintextedit-with-in-line-spell-check/ | |
| Copyright 2009 John Schember | |
| Copyright 2018 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 | |
| import enchant | |
| from enchant import tokenize | |
| from enchant.errors import TokenizerNotFoundError | |
| # pylint: disable=no-name-in-module | |
| from PyQt5.Qt import Qt | |
| from PyQt5.QtCore import QEvent | |
| from PyQt5.QtGui import (QFocusEvent, QSyntaxHighlighter, QTextCharFormat, | |
| QTextCursor) | |
| from PyQt5.QtWidgets import QAction, QApplication, QMenu, QPlainTextEdit | |
| class SpellTextEdit(QPlainTextEdit): | |
| """QPlainTextEdit subclass which does spell-checking using PyEnchant""" | |
| max_suggestion_limit = 20 | |
| def __init__(self, *args): | |
| QPlainTextEdit.__init__(self, *args) | |
| # Start with a default dictionary based on the current locale. | |
| self.highlighter = EnchantHighlighter(self.document()) | |
| self.highlighter.setDict(enchant.Dict()) | |
| def contextMenuEvent(self, event): | |
| """Custom context menu handler to add a spelling suggestions submenu""" | |
| # TODO: Use the version of createStandardContextMenu which takes | |
| # QPoint(event.x(), event.y()) once I don't need to support Qt versions | |
| # before 5.5. (It's recommended as it allows more contextual contents) | |
| popup_menu = self.createStandardContextMenu() | |
| # Create a cursor object selecting the word under the mouse pointer | |
| # FIXME: This method tokenizes differently than the highlighter and | |
| # allows one to right-click an un-highlighted URL and find a | |
| # suggestions menu when there shouldn't be one. | |
| cursor = self.cursorForPosition(event.pos()) | |
| cursor.select(QTextCursor.WordUnderCursor) | |
| # Check if the selected word is misspelled and offer spelling | |
| # suggestions if it is | |
| if cursor.hasSelection(): | |
| text = cursor.selectedText() | |
| spl_dict = self.highlighter.dict() | |
| if not spl_dict.check(text): | |
| spell_menu = QMenu('Spelling Suggestions') | |
| spell_menu.triggered.connect(self.cb_correct_word) | |
| # TODO: Use enchant.utils.trim_suggestions once I don't have to | |
| # support old PyEnchant versions. | |
| for word in spl_dict.suggest(text)[:self.max_suggestion_limit]: | |
| action = QAction(word, spell_menu) | |
| action.setData((cursor, word)) | |
| spell_menu.addAction(action) | |
| # Only prepend "Spelling Suggestions" submenu if it's non-empty | |
| if len(spell_menu.actions()) != 0: | |
| popup_menu.insertSeparator(popup_menu.actions()[0]) | |
| popup_menu.insertMenu(popup_menu.actions()[0], spell_menu) | |
| popup_menu.exec_(event.globalPos()) | |
| # Fix bug observed in Qt 5.2.1 on *buntu 14.04 LTS where: | |
| # 1. The cursor remains invisible after closing the context menu | |
| # 2. Keyboard input causes it to appear, but it doesn't blink | |
| # 3. Switching focus away from and back to the window fixes it | |
| self.focusInEvent(QFocusEvent(QEvent.FocusIn)) | |
| def cb_correct_word(self, action): # pylint: disable=no-self-use | |
| """Event handler Handler for 'Spelling Suggestions' entries.""" | |
| cursor, word = action.data() | |
| cursor.beginEditBlock() | |
| cursor.removeSelectedText() | |
| cursor.insertText(word) | |
| cursor.endEditBlock() | |
| class EnchantHighlighter(QSyntaxHighlighter): | |
| """QSyntaxHighlighter subclass which consults a PyEnchant dictionary""" | |
| tokenizer = None | |
| token_filters = (tokenize.EmailFilter, tokenize.URLFilter) | |
| def __init__(self, *args): | |
| QSyntaxHighlighter.__init__(self, *args) | |
| self._sp_dict = None | |
| # Define the spellcheck style once and assign it as necessary | |
| # XXX: This will probably cause problems if I need to set underline | |
| # styles on rich text. | |
| self.err_format = QTextCharFormat() | |
| self.err_format.setUnderlineColor(Qt.red) | |
| self.err_format.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline) | |
| def dict(self): | |
| """Gets the spelling dictionary in use""" | |
| return self._sp_dict | |
| def setDict(self, sp_dict): | |
| """Sets the spelling dictionary to be used""" | |
| self._sp_dict = sp_dict | |
| try: | |
| self.tokenizer = tokenize.get_tokenizer( | |
| self._sp_dict.tag, filters=self.token_filters) | |
| except TokenizerNotFoundError: | |
| # Fall back to the "good for most euro languages" English tokenizer | |
| self.tokenizer = tokenize.get_tokenizer(filters=self.token_filters) | |
| self.rehighlight() | |
| def highlightBlock(self, text): | |
| """Overridden QSyntaxHighlighter method to apply the highlight""" | |
| if not self._sp_dict: | |
| return | |
| for (word, pos) in self.tokenizer(text): | |
| if not self._sp_dict.check(word): | |
| self.setFormat(pos, len(word), self.err_format) | |
| if __name__ == '__main__': | |
| app = QApplication(sys.argv) | |
| spellEdit = SpellTextEdit() | |
| spellEdit.show() | |
| sys.exit(app.exec_()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment