| 1 |
# |
| 2 |
# Copyright (c) 2010 Doug Hellmann. All rights reserved. |
| 3 |
# |
| 4 |
"""Spelling checker extension for Sphinx. |
| 5 |
""" |
| 6 |
|
| 7 |
try: |
| 8 |
import enchant |
| 9 |
from enchant.tokenize import get_tokenizer |
| 10 |
except ImportError as imp_exc: |
| 11 |
enchant_import_error = imp_exc |
| 12 |
else: |
| 13 |
enchant_import_error = None |
| 14 |
|
| 15 |
|
| 16 |
class SpellingChecker: |
| 17 |
"""Checks the spelling of blocks of text. |
| 18 |
|
| 19 |
Uses options defined in the sphinx configuration file to control |
| 20 |
the checking and filtering behavior. |
| 21 |
""" |
| 22 |
|
| 23 |
def __init__(self, lang, suggest, word_list_filename, |
| 24 |
tokenizer_lang='en_US', filters=None, context_line=False): |
| 25 |
if enchant_import_error is not None: |
| 26 |
raise RuntimeError( |
| 27 |
'Cannot instantiate SpellingChecker ' |
| 28 |
'without PyEnchant installed', |
| 29 |
) from enchant_import_error |
| 30 |
if filters is None: |
| 31 |
filters = [] |
| 32 |
self.dictionary = enchant.DictWithPWL(lang, word_list_filename) |
| 33 |
self.tokenizer = get_tokenizer(tokenizer_lang, filters=filters) |
| 34 |
self.original_tokenizer = self.tokenizer |
| 35 |
self.suggest = suggest |
| 36 |
self.context_line = context_line |
| 37 |
|
| 38 |
def push_filters(self, new_filters): |
| 39 |
"""Add a filter to the tokenizer chain. |
| 40 |
""" |
| 41 |
t = self.tokenizer |
| 42 |
for f in new_filters: |
| 43 |
t = f(t) |
| 44 |
self.tokenizer = t |
| 45 |
|
| 46 |
def pop_filters(self): |
| 47 |
"""Remove the filters pushed during the last call to push_filters(). |
| 48 |
""" |
| 49 |
self.tokenizer = self.original_tokenizer |
| 50 |
|
| 51 |
def check(self, text): |
| 52 |
"""Yields bad words and suggested alternate spellings. |
| 53 |
""" |
| 54 |
for word, pos in self.tokenizer(text): |
| 55 |
correct = self.dictionary.check(word) |
| 56 |
if correct: |
| 57 |
continue |
| 58 |
|
| 59 |
suggestions = self.dictionary.suggest(word) if self.suggest else [] |
| 60 |
line = line_of_index(text, pos) if self.context_line else "" |
| 61 |
line_offset = text.count("\n", 0, pos) |
| 62 |
|
| 63 |
yield word, suggestions, line, line_offset |
| 64 |
|
| 65 |
|
| 66 |
def line_of_index(text, index): |
| 67 |
try: |
| 68 |
line_start = text.rindex("\n", 0, index) + 1 |
| 69 |
except ValueError: |
| 70 |
line_start = 0 |
| 71 |
try: |
| 72 |
line_end = text.index("\n", index) |
| 73 |
except ValueError: |
| 74 |
line_end = len(text) |
| 75 |
|
| 76 |
return text[line_start:line_end] |