Files
novelWriter/novelwriter/core/spellcheck.py
T
Veronica Berglyd Olsen 1c45331b0a Fix and optimise code (#904)
* Fix bug in early error reporting in main init
* Update docstrings and optimise code in GuiMain
* Update docstrings and optimise code in Config
* Update docstrings and optimise code in common module
* Update docstrings and optimise code in main project classes
* Update the OptionState class
* Update the spell checker class
* Update the file converter classes and extend tests
* Update the about, merge, split and item editor classes and extend tests
* Update item editor test
* Update about dialog tests
* Some minor test cleanup
* Fix typo and add clarification in contributing guide
2021-10-14 21:35:42 +02:00

196 lines
5.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
novelWriter Spell Check Classes
=================================
Wrapper classes for spell checking tools
File History:
Created: 2019-06-11 [0.1.5]
This file is a part of novelWriter
Copyright 20182021, Veronica Berglyd Olsen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import os
import logging
import novelwriter
logger = logging.getLogger(__name__)
class NWSpellEnchant():
def __init__(self):
self.mainConf = novelwriter.CONFIG
self._theDict = None
self._projDict = set()
self._projectDict = None
self._spellLanguage = None
self._theBroker = None
logger.debug("Enchant spell checking activated")
return
##
# Getters and Setters
##
def spellLanguage(self):
return self._spellLanguage
def setLanguage(self, theLang, projectDict=None):
"""Load a dictionary for the language specified in the config.
If that fails, we load a mock dictionary so that lookups don't
crash.
"""
try:
import enchant
if self._theBroker is not None:
logger.debug("Deleting old pyenchant broker")
del self._theBroker
self._theBroker = enchant.Broker()
self._theDict = self._theBroker.request_dict(theLang)
self._spellLanguage = theLang
logger.debug("Enchant spell checking for language '%s' loaded", theLang)
except Exception:
logger.error("Failed to load enchant spell checking for language '%s'", theLang)
self._theDict = FakeEnchant()
self._spellLanguage = None
self._readProjectDictionary(projectDict)
for pWord in self._projDict:
self._theDict.add_to_session(pWord)
return
##
# Methods
##
def checkWord(self, theWord):
"""Wrapper function for pyenchant.
"""
return self._theDict.check(theWord)
def suggestWords(self, theWord):
"""Wrapper function for pyenchant.
"""
return self._theDict.suggest(theWord)
def addWord(self, newWord):
"""Add a word to the project dictionary.
"""
self._theDict.add_to_session(newWord)
if self._projectDict is not None and newWord not in self._projDict:
newWord = newWord.strip()
try:
with open(self._projectDict, mode="a+", encoding="utf-8") as outFile:
outFile.write("%s\n" % newWord)
self._projDict.add(newWord)
except Exception:
logger.error("Failed to add word to project word list %s", str(self._projectDict))
novelwriter.logException()
return False
return True
return False
def listDictionaries(self):
"""Wrapper function for pyenchant.
"""
retList = []
try:
import enchant
for spTag, spProvider in enchant.list_dicts():
retList.append((spTag, spProvider.name))
except Exception:
logger.error("Failed to list languages for enchant spell checking")
return retList
def describeDict(self):
"""Return the tag and provider of the currently loaded
dictionary.
"""
try:
spTag = self._theDict.tag
spName = self._theDict.provider.name
except Exception:
logger.error("Failed to extract information about the dictionary")
novelwriter.logException()
spTag = ""
spName = ""
return spTag, spName
##
# Internal Functions
##
def _readProjectDictionary(self, projectDict):
"""Read the content of the project dictionary, and add it to the
lookup lists.
"""
self._projDict = set()
self._projectDict = projectDict
if projectDict is None:
return False
if not os.path.isfile(projectDict):
return False
try:
logger.debug("Loading project word list")
with open(projectDict, mode="r", encoding="utf-8") as wordsFile:
for theLine in wordsFile:
theLine = theLine.strip()
if len(theLine) > 0 and theLine not in self._projDict:
self._projDict.add(theLine)
logger.debug("Project word list contains %d words", len(self._projDict))
except Exception:
logger.error("Failed to load project word list")
novelwriter.logException()
return False
return True
# END Class NWSpellEnchant
class FakeEnchant:
"""Fallback for when Enchant is selected, but not installed.
"""
def __init__(self):
return
def check(self, theWord):
return True
def suggest(self, theWord):
return []
def add_to_session(self, theWord):
return
# END Class FakeEnchant