Debian Codegraph @

src/tools/nuspell.cxx

raw symbols SCIP
1 /* Copyright 2016-2024 Dimitrij Mijoski
2 *
3 * This file is part of Nuspell.
4 *
5 * Nuspell is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * Nuspell is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with Nuspell. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <nuspell/dictionary.hxx>
20 #include <nuspell/finder.hxx>
21
22 #include <cassert>
23 #include <clocale>
24 #include <fstream>
25 #include <iomanip>
26 #include <iostream>
27 #include <unicode/brkiter.h>
28 #include <unicode/ucnv.h>
29
30 #include <getopt.h>
31
32 #if __has_include(<unistd.h>)
33 #include <unistd.h> // defines _POSIX_VERSION
34 #endif
35 #ifdef _POSIX_VERSION
36 #include <langinfo.h>
37 #endif
38 #ifdef _WIN32
39 #include <io.h>
40 #ifndef NOMINMAX
41 #define NOMINMAX
42 #endif
43 #define WIN32_LEAN_AND_MEAN
44 #include <windows.h>
45 #endif
46
47 // manually define if not supplied by the build system
48 #ifndef PROJECT_VERSION
49 #define PROJECT_VERSION "unknown.version"
50 #endif
51
52 using namespace std;
53 using nuspell::Dictionary, nuspell::Dictionary_Loading_Error,
54 nuspell::Dict_Finder_For_CLI_Tool_2;
55 namespace {
56 enum Mode { NORMAL, HELP, VERSION, LIST_DICTS };
57 auto print_help(const char* program_name) -> void
58 {
59 auto p = string_view(program_name);
60 auto& o = cout;
61 o << "Usage:\n"
62 << p << " [-d dict_NAME] [OPTION]... [FILE...]\n"
63 << p << " -D|--help|--version\n"
64 << R"(
65 Check spelling of each FILE. If no FILE is specified, check standard input.
66 The text in the input is first segmented into words with an algorithm
67 that recognizes punctuation and then each word is checked.
68
69 -d, --dictionary=di_CT use di_CT dictionary, only one is supported
70 -D, --list-dictionaries print search paths and available dictionaries
71 --encoding=enc set both input and output encoding
72 --input-encoding=enc input encoding, default is active locale
73 --output-encoding=enc output encoding, default is active locale
74 --help print this help
75 --version print version number
76
77 A dictionary consists of two files with extensions .dic and .aff. The -d option
78 accepts either dictionary name without filename extension, usually a language
79 tag, or a path (with slash) to the .aff file including the filename extension.
80 When just a name is given, it will be searched among the list of dictionaries in
81 the default directories (see option -D). When a path to .aff is given, only the
82 dictionary under the path is considered. When -d is not present, the CLI tools
83 tries to load a dictionary using the language tag from the active locale.
84
85 Returns error if the argument syntax is invalid, if the dictionary can not be
86 loaded or if some input file can not be opened. Otherwise, spell checking has
87 occurred and returns success.
88
89 The following environment variables can have effect:
90
91 DICTIONARY - same as -d,
92 DICPATH - additional directory path to search for dictionaries.
93
94 Example:
95 )"
96 << " " << p << " -d en_US file.txt\n"
97 << " " << p << " -d ../../subdir/di_CT.aff\n"
98 << R"(
99 Bug reports: <https://github.com/nuspell/nuspell/issues>
100 Full documentation: <https://github.com/nuspell/nuspell/wiki>
101 Home page: <http://nuspell.github.io/>
102 )";
103 }
104
105 auto ver_str = "nuspell " PROJECT_VERSION R"(
106 Copyright 2016-2024 Dimitrij Mijoski
107 License LGPLv3+: GNU LGPL version 3 or later <http://gnu.org/licenses/lgpl.html>.
108 This is free software: you are free to change and redistribute it.
109 There is NO WARRANTY, to the extent permitted by law.
110
111 Written by Dimitrij Mijoski.
112 )";
113
114 auto print_version() -> void { cout << ver_str; }
115
116 auto list_dictionaries(const Dict_Finder_For_CLI_Tool_2& f) -> void
117 {
118 if (empty(f.get_dir_paths())) {
119 cout << "No search paths available" << '\n';
120 }
121 else {
122 cout << "Search paths:" << '\n';
123 for (auto& p : f.get_dir_paths()) {
124 cout << p.string() << '\n';
125 }
126 }
127 auto dicts = vector<filesystem::path>();
128 nuspell::search_dirs_for_dicts(f.get_dir_paths(), dicts);
129 if (empty(dicts)) {
130 cout << "No dictionaries available\n";
131 }
132 else {
133 stable_sort(begin(dicts), end(dicts));
134 cout << "Available dictionaries:\n";
135 for (auto& d : dicts) {
136 cout << left << setw(15) << d.stem().string() << ' '
137 << d.string() << '\n';
138 }
139 }
140 }
141
142 auto from_utf8(string_view source, string& dest, UConverter* ucnv,
143 UErrorCode& uerr)
144 {
145 dest.resize(dest.capacity());
146 auto len =
147 ucnv_fromAlgorithmic(ucnv, UCNV_UTF8, dest.data(), dest.size(),
148 source.data(), source.size(), &uerr);
149 dest.resize(len);
150 if (uerr == U_BUFFER_OVERFLOW_ERROR) {
151 uerr = U_ZERO_ERROR;
152 ucnv_fromAlgorithmic(ucnv, UCNV_UTF8, dest.data(), dest.size(),
153 source.data(), source.size(), &uerr);
154 }
155 }
156
157 auto to_unicode_string(string_view source, icu::UnicodeString& dest,
158 UConverter* ucnv, UErrorCode& uerr)
159 {
160 auto buf = dest.getBuffer(-1);
161 auto len = ucnv_toUChars(ucnv, buf, dest.getCapacity(), source.data(),
162 source.size(), &uerr);
163 if (uerr == U_BUFFER_OVERFLOW_ERROR) {
164 uerr = U_ZERO_ERROR;
165 dest.releaseBuffer(0);
166 buf = dest.getBuffer(len);
167 if (!buf)
168 throw bad_alloc();
169 len = ucnv_toUChars(ucnv, buf, dest.getCapacity(),
170 source.data(), source.size(), &uerr);
171 }
172 dest.releaseBuffer(len);
173 }
174
175 auto process_word_utf8_output_enc(const Dictionary& dic, string_view word,
176 vector<string>& suggestions, ostream& out)
177 {
178 auto correct = dic.spell(word);
179 if (correct) {
180 out << "* OK\n";
181 return;
182 }
183 dic.suggest(word, suggestions);
184 if (suggestions.empty()) {
185 out << "# Wrong: " << word << ". No suggestions.\n";
186 return;
187 }
188 out << "& Wrong: " << word << ". How about: ";
189 out << suggestions[0];
190 for_each(begin(suggestions) + 1, end(suggestions),
191 [&](auto& sug) { out << ", " << sug; });
192 out << '\n';
193 }
194
195 auto process_word_any_output_enc(const Dictionary& dic, string_view u8word,
196 vector<string>& suggestions, ostream& out,
197 UConverter* out_cnv, UErrorCode& uerr)
198 {
199 auto correct = dic.spell(u8word);
200 if (correct) {
201 out << "* OK\n";
202 return;
203 }
204 dic.suggest(u8word, suggestions);
205 auto encoded_out = string();
206 from_utf8(u8word, encoded_out, out_cnv, uerr);
207 if (suggestions.empty()) {
208 out << "# Wrong: " << encoded_out << ". No suggestions.\n";
209 return;
210 }
211 out << "& Wrong: " << encoded_out << ". How about: ";
212 from_utf8(suggestions[0], encoded_out, out_cnv, uerr);
213 out << encoded_out;
214 for_each(begin(suggestions) + 1, end(suggestions),
215 [&](const string& u8sug) {
216 out << ", ";
217 from_utf8(u8sug, encoded_out, out_cnv, uerr);
218 out << encoded_out;
219 });
220 out << '\n';
221 }
222
223 auto is_word_break(int32_t typ)
224 {
225 return (UBRK_WORD_NUMBER <= typ && typ < UBRK_WORD_NUMBER_LIMIT) ||
226 (UBRK_WORD_LETTER <= typ && typ < UBRK_WORD_LETTER_LIMIT) ||
227 (UBRK_WORD_KANA <= typ && typ < UBRK_WORD_KANA_LIMIT) ||
228 (UBRK_WORD_IDEO <= typ && typ < UBRK_WORD_IDEO_LIMIT);
229 }
230
231 auto process_line_utf8_input_enc(const Dictionary& dic, const string& line,
232 UText* utext, icu::BreakIterator* ubrkiter,
233 vector<string>& suggestions, ostream& out,
234 UConverter* out_cnv, UErrorCode& uerr)
235 {
236 utext_openUTF8(utext, line.data(), line.size(), &uerr);
237 ubrkiter->setText(utext, uerr);
238 auto is_utf8_out = ucnv_getType(out_cnv) == UCNV_UTF8;
239 for (auto i = ubrkiter->first(), prev = 0; i != ubrkiter->DONE;
240 prev = i, i = ubrkiter->next()) {
241 auto typ = ubrkiter->getRuleStatus();
242 if (is_word_break(typ)) {
243 auto word = string_view(line).substr(prev, i - prev);
244 if (is_utf8_out)
245 process_word_utf8_output_enc(dic, word,
246 suggestions, out);
247 else
248 process_word_any_output_enc(
249 dic, word, suggestions, out, out_cnv, uerr);
250 }
251 }
252 assert(U_SUCCESS(uerr));
253 }
254
255 auto process_line_any_input_enc(const Dictionary& dic, const string& line,
256 icu::UnicodeString& uline, UConverter* in_cnv,
257 icu::BreakIterator* ubrkiter, UErrorCode& uerr,
258 string& u8word, vector<string>& suggestions,
259 ostream& out, UConverter* out_cnv)
260 {
261 to_unicode_string(line, uline, in_cnv, uerr);
262 ubrkiter->setText(uline);
263 /* size_t orig_prev = 0, orig_i = 0;
264 auto src = line.c_str();
265 auto src_end = src + line.size(); */
266 auto is_utf8_out = ucnv_getType(out_cnv) == UCNV_UTF8;
267 ucnv_resetToUnicode(in_cnv);
268 for (auto i = ubrkiter->first(), prev = 0; i != ubrkiter->DONE;
269 prev = i, i = ubrkiter->next() /*, orig_prev = orig_i*/) {
270
271 /* for (auto j = prev; j != i; ++j) {
272 auto cp =
273 ucnv_getNextUChar(in_cnv, &src, src_end, &uerr);
274
275 // U_IS_SURROGATE(uline[j]) or
276 // U_IS_LEAD(uline[j]) can work too
277 j += !U_IS_BMP(cp);
278 }
279 orig_i = distance(line.c_str(), src); */
280
281 auto typ = ubrkiter->getRuleStatus();
282 if (is_word_break(typ)) {
283 auto uword = uline.tempSubStringBetween(prev, i);
284 u8word.clear();
285 uword.toUTF8String(u8word);
286 /* auto enc_word = string_view(line).substr(
287 orig_prev, orig_i - orig_prev); */
288
289 if (is_utf8_out)
290 process_word_utf8_output_enc(dic, u8word,
291 suggestions, out);
292 else
293 process_word_any_output_enc(dic, u8word,
294 suggestions, out,
295 out_cnv, uerr);
296 }
297 }
298 assert(U_SUCCESS(uerr));
299 }
300
301 auto process_text(const Dictionary& dic, istream& in, UConverter* in_cnv,
302 ostream& out, UConverter* out_cnv, UErrorCode& uerr)
303 {
304 auto line = string();
305 auto suggestions = vector<string>();
306 auto wrong_words = vector<string_view>();
307
308 // TODO: try to use Locale constructed from dictionary name.
309 auto ubrkiter = unique_ptr<icu::BreakIterator>(
310 icu::BreakIterator::createWordInstance(icu::Locale(), uerr));
311 auto utext = icu::LocalUTextPointer(
312 utext_openUTF8(nullptr, line.data(), line.size(), &uerr));
313 auto uline = icu::UnicodeString();
314 auto u8word = string();
315 auto is_utf8 = ucnv_getType(in_cnv) == UCNV_UTF8;
316
317 if (&in == &cin)
318 out << "Enter some text: ";
319 while (getline(in, line)) {
320 wrong_words.clear();
321 if (is_utf8)
322 process_line_utf8_input_enc(dic, line, utext.getAlias(),
323 ubrkiter.get(), suggestions,
324 out, out_cnv, uerr);
325 else
326 process_line_any_input_enc(dic, line, uline, in_cnv,
327 ubrkiter.get(), uerr, u8word,
328 suggestions, out, out_cnv);
329
330 out << '\n'; // In NORMAL mode put empty line for each input
331 // line.
332 }
333 }
334 } // namespace
335 int main(int argc, char* argv[])
336 {
337 auto mode_int = int(Mode::NORMAL);
338 auto program_name = "nuspell";
339 auto dictionary = string();
340 auto input_enc = string();
341 auto output_enc = string();
342
343 if (argc > 0 && argv[0])
344 program_name = argv[0];
345
346 ios_base::sync_with_stdio(false);
347
348 auto optstring = "d:D";
349 option longopts[] = {
350 {"help", no_argument, &mode_int, Mode::HELP},
351 {"version", no_argument, &mode_int, Mode::VERSION},
352 {"list-dictionaries", no_argument, &mode_int, Mode::LIST_DICTS},
353 {"dictionary", required_argument, nullptr, 'd'},
354 {"encoding", required_argument, nullptr, 'e'},
355 {"input-encoding", required_argument, nullptr, 'i'},
356 {"output-encoding", required_argument, nullptr, 'o'},
357 {}};
358 int longindex;
359 int c;
360 while ((c = getopt_long(argc, argv, optstring, longopts, &longindex)) !=
361 -1) {
362 switch (c) {
363 case 0:
364 // check longopts[longindex] if needed
365 break;
366 case 'd':
367 dictionary = optarg;
368 break;
369 case 'D':
370 mode_int = Mode::LIST_DICTS;
371 break;
372 case 'e':
373 input_enc = optarg;
374 output_enc = optarg;
375 break;
376 case 'i':
377 input_enc = optarg;
378 break;
379 case 'o':
380 output_enc = optarg;
381 break;
382 case '?':
383 return EXIT_FAILURE;
384 }
385 }
386 auto mode = static_cast<Mode>(mode_int);
387 if (mode == Mode::VERSION) {
388 print_version();
389 return 0;
390 }
391 else if (mode == Mode::HELP) {
392 print_help(program_name);
393 return 0;
394 }
395 auto f = Dict_Finder_For_CLI_Tool_2();
396 if (mode == Mode::LIST_DICTS) {
397 list_dictionaries(f);
398 return 0;
399 }
400
401 char* loc_str = nullptr;
402 #if _WIN32
403 loc_str = setlocale(LC_CTYPE, nullptr); // will return "C"
404
405 /* On Windows, the console is a buggy thing. If the default C locale is
406 active, then the encoding of the strings gotten from C or C++ stdio
407 (fgets, scanf, cin) is GetConsoleCP(). Stdout accessed via standard
408 functions (printf, cout) expects encoding of GetConsoleOutputCP() which
409 is the same as GetConsoleCP() unless manually changed. By default both
410 are the active OEM encoding, unless changed with the command chcp, or by
411 calling the Set functions.
412
413 If we call setlocale(LC_CTYPE, ""), or let's say setlocale(LC_CTYPE,
414 ".1251"), then stdin will still return in the encoding GetConsoleCP(),
415 but stdout functions like printf now will expect a different encoding,
416 the one set via setlocale. Because of this mess don't change locale with
417 setlocale on Windows.
418
419 When stdin or stout are redirected from/to file or another terminal like
420 the one in MSYS2, they are read/written as-is. Then we will assume UTF-8
421 encoding. */
422 #else
423 loc_str = setlocale(LC_CTYPE, "");
424 if (!loc_str) {
425 clog << "WARNING: Can not set to system locale, fall back to "
426 "\"C\".\n";
427 loc_str = setlocale(LC_CTYPE, nullptr); // will return "C"
428 }
429 #endif
430 #if _POSIX_VERSION
431 auto enc_str = nl_langinfo(CODESET);
432 if (input_enc.empty())
433 input_enc = enc_str;
434 if (output_enc.empty())
435 output_enc = enc_str;
436 #elif _WIN32
437 if (optind == argc && _isatty(_fileno(stdin)))
438 input_enc = "cp" + to_string(GetConsoleCP());
439 else if (input_enc.empty())
440 input_enc = "UTF-8";
441 if (_isatty(_fileno(stdout)))
442 output_enc = "cp" + to_string(GetConsoleOutputCP());
443 else if (output_enc.empty())
444 output_enc = "UTF-8";
445 #endif
446 auto loc_str_sv = string_view(loc_str);
447 clog << "INFO: Locale LC_CTYPE=" << loc_str_sv
448 << ", Input encoding=" << input_enc
449 << ", Output encoding=" << output_enc << endl;
450
451 if (dictionary.empty()) {
452 auto denv = getenv("DICTIONARY");
453 if (denv)
454 dictionary = denv;
455 }
456 if (dictionary.empty()) {
457 // infer dictionary from locale
458 auto idx = min(loc_str_sv.find('.'), loc_str_sv.find('@'));
459 dictionary = loc_str_sv.substr(0, idx);
460 }
461 if (dictionary.empty()) {
462 clog << "ERROR: No dictionary provided and can not infer from "
463 "OS locale\n";
464 return EXIT_FAILURE;
465 }
466 auto filename = f.get_dictionary_path(dictionary);
467 if (filename.empty()) {
468 clog << "ERROR: Dictionary " << dictionary << " not found\n";
469 return EXIT_FAILURE;
470 }
471 clog << "INFO: Pointed dictionary " << filename.string() << endl;
472 auto dic = Dictionary();
473 try {
474 dic.load_aff_dic_internal(filename, clog);
475 }
476 catch (const Dictionary_Loading_Error& e) {
477 clog << "ERROR: " << e.what() << '\n';
478 return EXIT_FAILURE;
479 }
480 // ICU reports all types of errors, logic errors and runtime errors
481 // using this enum. We should not check for logic errors, they should
482 // not happened. Optionally, only assert that they are not there can be
483 // used. We should check for runtime errors.
484 // The encoding conversion is a common case where runtime error can
485 // happen, but by default ICU uses Unicode replacement character on
486 // errors and reports success. This can be changed, but there is no need
487 // for that.
488 auto uerr = U_ZERO_ERROR;
489 auto inp_enc_cstr = input_enc.c_str();
490 if (input_enc.empty()) {
491 inp_enc_cstr = nullptr;
492 clog << "WARNING: using default ICU encoding converter for IO"
493 << endl;
494 }
495 auto in_ucnv =
496 icu::LocalUConverterPointer(ucnv_open(inp_enc_cstr, &uerr));
497 if (U_FAILURE(uerr)) {
498 clog << "ERROR: Invalid encoding " << input_enc << ".\n";
499 return EXIT_FAILURE;
500 }
501
502 auto out_ucnv_smart_ptr = icu::LocalUConverterPointer();
503 auto out_ucnv = in_ucnv.getAlias(); // often output_enc is same as input
504 if (output_enc != input_enc) {
505 auto output_enc_cstr = output_enc.c_str();
506 if (output_enc.empty()) {
507 output_enc_cstr = nullptr;
508 clog << "WARNING: using default ICU encoding converter "
509 "for IO"
510 << endl;
511 }
512 out_ucnv = ucnv_open(output_enc_cstr, &uerr);
513 out_ucnv_smart_ptr.adoptInstead(out_ucnv);
514 if (U_FAILURE(uerr)) {
515 clog << "ERROR: Invalid encoding " << output_enc
516 << ".\n";
517 return EXIT_FAILURE;
518 }
519 }
520
521 if (optind == argc) {
522 process_text(dic, cin, in_ucnv.getAlias(), cout, out_ucnv,
523 uerr);
524 }
525 else {
526 for (; optind != argc; ++optind) {
527 auto file_name = argv[optind];
528 ifstream in(file_name);
529 if (!in.is_open()) {
530 clog << "ERROR: Can't open " << file_name
531 << '\n';
532 return EXIT_FAILURE;
533 }
534 process_text(dic, in, in_ucnv.getAlias(), cout,
535 out_ucnv, uerr);
536 }
537 }
538 }