1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
|
# Copyright © 2013-2023 Jakub Wilk <jwilk@jwilk.net>
#
# 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.
'''
the command-line interface
'''
import argparse
import functools
import io
import re
import signal
import sys
import types
import enchant.tokenize
class lib:
# pylint: disable=import-outside-toplevel
from . import colors
from . import data
from . import extdict
from . import intdict
from . import pager
from . import text
# pylint: enable=import-outside-toplevel
__version__ = '0.7.10'
class VersionAction(argparse.Action):
def __init__(self, option_strings, dest=argparse.SUPPRESS):
super().__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
help='show version information and exit'
)
def __call__(self, parser, namespace, values, option_string=None):
# pylint: disable=consider-using-f-string
print(f'{parser.prog} {__version__}')
print('+ Python {0}.{1}.{2}'.format(*sys.version_info))
print(f'+ PyEnchant {enchant.__version__}')
try:
enchant_version = enchant.get_enchant_version()
except AttributeError:
pass
else:
if isinstance(enchant_version, bytes):
enchant_version = enchant_version.decode('ASCII', 'replace')
print(f' + Enchant {enchant_version}')
regex = lib.intdict.re
print(f'+ regex {regex.__version__}') # pylint: disable=no-member
parser.exit()
def main():
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
ap = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
ap.add_argument('--version', action=VersionAction)
ap.add_argument('files', metavar='FILE', nargs='*', default=['-'],
help='file to process (default: stdin)')
ap.add_argument('-l', '--language', metavar='LANG', default='en',
help='spell-check for this language (default: "en")')
ap.add_argument('--list-languages', nargs=0, action=list_languages,
help='print list of available languages')
ap.add_argument('--blacklist', metavar='FILE', action='append', default=[],
help='use misspelling dictionary')
ap.add_argument('--camel-case', action='store_true',
help='split camel-cased compound words')
ap.add_argument('--input-encoding', metavar='ENC', default='UTF-8:replace',
help='assume input encoding ENC (default: "UTF-8:replace")')
default_output_format = 'color' if sys.stdout.isatty() else 'plain'
ap.add_argument('-f', '--output-format', choices=('plain', 'color'), default=default_output_format,
help=(
'"plain" = use "^" to emphasize words\n'
'"color" = highlight words in color (default on tty)\n'
)
)
ap.add_argument('-r', '--reverse', action='store_true',
help='print most frequent words first')
ap.add_argument('--compact', action='store_true',
help='omit blank lines in output')
ap.add_argument('--limit', metavar='N', type=int, default=1e999,
help='skip words that have >N instances')
ap.add_argument('--max-context-width', type=int, metavar='N', default=30,
help='limit context width to N chars')
ap.add_argument('--suggest', metavar='N', type=int, default=0,
help='suggest up to N corrections')
ap.add_argument('--debug-dict', action='store_true', help=argparse.SUPPRESS)
ap.add_argument('--traceback', action='store_true', help=argparse.SUPPRESS)
options = ap.parse_args()
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, 'UTF-8')
try:
split_words = enchant.tokenize.get_tokenizer(options.language)
except enchant.errors.TokenizerNotFoundError:
split_words = enchant.tokenize.get_tokenizer(None)
if options.camel_case:
split_words = lib.text.camel_case_tokenizer(split_words)
if options.language == 'und':
dictionary = None
spellcheck = ''.__gt__ # always returns False
options.suggest = 0
else:
dictionary = enchant.Dict(options.language)
spellcheck = functools.lru_cache(maxsize=None)(
dictionary.check
)
if options.debug_dict:
if dictionary is None:
dictvars = {}
else:
dictvars = vars(dictionary).items()
for key, value in sorted(dictvars):
print(f'{key} = {value!r}')
sys.exit(0)
intdict = lib.intdict.Dictionary(options.language)
extdict = lib.extdict.Dictionary(*options.blacklist)
misspellings = lib.data.Misspellings()
encoding = options.input_encoding
enc_errors = 'strict'
if ':' in encoding:
[encoding, enc_errors] = encoding.rsplit(':', 1)
ctxt = types.SimpleNamespace(
dictionary=dictionary,
intdict=intdict,
extdict=extdict,
split_words=split_words,
spellcheck=spellcheck,
misspellings=misspellings,
options=options,
)
rc = 0
for path in options.files:
if path == '-':
file = io.TextIOWrapper(
sys.stdin.buffer,
encoding=encoding,
errors=enc_errors,
)
else:
try:
file = open( # pylint: disable=consider-using-with
path, 'rt',
encoding=encoding,
errors=enc_errors,
)
except OSError as exc:
if options.traceback:
raise
msg = f'{ap.prog}: {path}: {exc.strerror}'
print(msg, file=sys.stderr)
rc = 1
continue
with file:
spellcheck_file(ctxt, file)
if not misspellings:
sys.exit(rc)
raw_cc = options.output_format == 'color'
try:
with lib.pager.autopager(raw_control_chars=raw_cc):
print_misspellings(ctxt)
except lib.pager.Error:
if options.traceback:
raise
msg = f'{ap.prog}: pager failed'
print(msg, file=sys.stderr)
rc = 1
sys.exit(rc)
def spellcheck_file(ctxt, file):
force_ucs2 = (
ctxt.dictionary is not None and
ctxt.dictionary.provider.name == 'myspell'
)
for line in file:
if force_ucs2:
# https://github.com/rfk/pyenchant/issues/58
line = re.sub(r'[^\0-\uFFFF]', '\uFFFD', line)
line = line.strip()
line = line.expandtabs()
taken = bytearray(len(line))
for word, pos in ctxt.split_words(line):
assert len(word) >= 1
if word in ctxt.extdict:
certainty = 1
elif ctxt.spellcheck(word):
continue
elif ctxt.intdict.is_whitelisted(word):
continue
else:
certainty = 0
for i, dummy in enumerate(word, start=pos):
taken[i] = True
ctxt.misspellings.add(word, line, pos, certainty)
for word, pos in ctxt.intdict.find(line):
assert len(word) >= 1
for i, dummy in enumerate(word, start=pos):
if taken[i]:
break
else:
ctxt.misspellings.add(word, line, pos, 1)
def print_misspellings(ctxt):
rare_misspellings = lib.data.Misspellings()
for word, occurrences in ctxt.misspellings.sorted_words():
if len(occurrences) == 1:
[(word, line, positions)] = occurrences
for pos, certainty in positions.items():
rare_misspellings.add(word, line, pos, certainty)
ctxt.rare_misspellings = rare_misspellings
if ctxt.options.reverse:
print_common_misspellings(ctxt)
print_rare_misspellings(ctxt)
else:
print_rare_misspellings(ctxt)
print_common_misspellings(ctxt)
def print_common_misspellings(ctxt):
options = ctxt.options
for word, occurrences in ctxt.misspellings.sorted_words(reverse=options.reverse):
if len(occurrences) == 1:
continue
if occurrences.count() > options.limit:
continue
extra = ''
if options.suggest > 0:
suggestions = ctxt.dictionary.suggest(word)[:options.suggest]
if suggestions:
suggestions = str.join(', ', suggestions)
extra = f' ({suggestions})'
print(word + extra + ':')
highlight_color = 'error' if occurrences.certainty > 0 else 'warn'
occurrences = [
(
lib.text.ltrim(lcontext, options.max_context_width),
word,
lib.text.rtrim(rcontext, options.max_context_width),
)
for lcontext, word, rcontext
in occurrences.sorted_context()
]
lwidth = max(len(lcontext) for lcontext, _, _, in occurrences)
for lcontext, word, rcontext in occurrences: # pylint: disable=redefined-outer-name
lcontext = lcontext.rjust(lwidth)
if options.output_format == 'color':
lcontext = lib.colors.escape(lcontext)
word = lib.colors.highlight(word, highlight_color)
rcontext = lib.colors.escape(rcontext)
print(lib.colors.dim('|'), end=' ')
else:
print('|', end=' ')
print(f'{lcontext}{word}{rcontext}')
if options.output_format != 'color':
print('', ' ' * lwidth, '^' * len(word))
if not options.compact:
print()
def print_rare_misspellings(ctxt):
options = ctxt.options
use_color = options.output_format == 'color'
for line, occurrences in ctxt.rare_misspellings.sorted_lines(reverse=options.reverse):
header = []
underline = bytearray(b' ' * len(line))
for word, line, positions in sorted(occurrences): # pylint: disable=redefined-outer-name
if use_color and (max(positions.values()) > 0):
underline_char = b'!'
else:
underline_char = b'^'
if len(positions) > options.limit:
continue
extra = ''
if options.suggest > 0:
suggestions = ctxt.dictionary.suggest(word)[:options.suggest]
if suggestions:
suggestions = str.join(', ', suggestions)
extra = f' ({suggestions})'
header += [word + extra]
for x in positions:
underline[x : x + len(word)] = underline_char * len(word)
if not header:
continue
print(str.join(', ', header) + ':')
underline = underline.decode()
lwidth = len(underline) - len(underline.lstrip())
rwidth = len(underline) - len(underline.rstrip())
lexceed = lwidth - options.max_context_width
rexceed = rwidth - options.max_context_width
if lexceed > 0:
lwidth = len(line) - lexceed
line = lib.text.ltrim(line, lwidth)
underline = lib.text.ltrim(underline, lwidth, char=' ')
if rexceed > 0:
rwidth = len(line) - rexceed
line = lib.text.rtrim(line, rwidth)
underline = lib.text.rtrim(underline, rwidth, char=' ')
if use_color:
hline = lib.colors.highlight(
line, (
'warn' if u == '^' else
'error' if u == '!' else
'off'
for u in underline
)
)
print(lib.colors.dim('|'), hline)
else:
print('|', line)
print(' ', underline.rstrip())
if not options.compact:
print()
class list_languages(argparse.Action):
def __call__(self, *args, **kwargs): # pylint: disable=arguments-differ,signature-differs
for lang in sorted(enchant.list_languages()):
print(lang)
sys.exit(0)
__all__ = ['main']
# vim:ts=4 sts=4 sw=4 et
|