2 * \file GuiSpellchecker.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
9 * Full author contact details are available in file CREDITS.
14 #include "GuiSpellchecker.h"
16 #include "qt_helpers.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
22 #include "CutAndPaste.h"
27 #include "Paragraph.h"
29 #include "support/textutils.h"
30 #include "support/convert.h"
31 #include "support/docstring.h"
33 #include <QProgressBar>
35 #include <QPushButton>
36 #include <QListWidget>
37 #include <QListWidgetItem>
38 #include <QCloseEvent>
39 #include <QSyntaxHighlighter>
40 #include <QTextCharFormat>
41 #include <QTextDocument>
43 #if defined(USE_ASPELL)
44 # include "ASpell_local.h"
45 #elif defined(USE_PSPELL)
49 #if defined(USE_ISPELL)
52 # include "SpellBase.h"
55 #include "frontends/alert.h"
56 // FIXME: those two headers are needed because of the
57 // WorkArea::redraw() call below.
58 #include "frontends/LyXView.h"
59 #include "frontends/WorkArea.h"
70 using support::bformat;
71 using support::contains;
73 GuiSpellchecker::GuiSpellchecker(LyXView & lv)
74 : GuiDialog(lv, "spellchecker"), exitEarly_(false),
75 oldval_(0), newvalue_(0), count_(0), speller_(0)
78 setViewTitle(_("Spellchecker"));
80 connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
81 connect(replacePB, SIGNAL(clicked()), this, SLOT(replace()));
82 connect(ignorePB, SIGNAL(clicked()), this, SLOT(ignore()));
83 connect(replacePB_3, SIGNAL(clicked()), this, SLOT(accept()));
84 connect(addPB, SIGNAL(clicked()), this, SLOT(add()));
86 connect(replaceCO, SIGNAL(highlighted(QString)),
87 this, SLOT(replaceChanged(QString)));
88 connect(suggestionsLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
89 this, SLOT(replace()));
90 connect(suggestionsLW, SIGNAL(itemClicked(QListWidgetItem*)),
91 this, SLOT(suggestionChanged(QListWidgetItem*)));
93 wordED->setReadOnly(true);
95 bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
96 bc().setCancel(closePB);
100 GuiSpellchecker::~GuiSpellchecker()
106 void GuiSpellchecker::suggestionChanged(QListWidgetItem * item)
108 if (replaceCO->count() != 0)
109 replaceCO->setItemText(0, item->text());
111 replaceCO->addItem(item->text());
113 replaceCO->setCurrentIndex(0);
117 void GuiSpellchecker::replaceChanged(const QString & str)
119 if (suggestionsLW->currentItem()->text() == str)
122 for (int i = 0; i != suggestionsLW->count(); ++i) {
123 if (suggestionsLW->item(i)->text() == str) {
124 suggestionsLW->setCurrentRow(i);
131 void GuiSpellchecker::closeEvent(QCloseEvent * e)
134 GuiDialog::closeEvent(e);
138 void GuiSpellchecker::reject()
145 void GuiSpellchecker::updateContents()
147 // The clauses below are needed because the spellchecker
148 // has many flaws (see bugs 1950, 2218).
149 // Basically, we have to distinguish the case where a
150 // spellcheck has already been performed for the whole
151 // document (exitEarly() == true, isVisible() == false)
152 // from the rest (exitEarly() == false, isVisible() == true).
153 // FIXME: rewrite the whole beast!
154 static bool check_after_early_exit;
156 // a spellcheck has already been performed,
158 check_after_early_exit = true;
160 else if (isVisible()) {
161 // the above check triggers a second update,
162 // and isVisible() is true then. Prevent a
163 // second check that skips the first word
164 if (check_after_early_exit)
165 // don't check, but reset the bool.
166 // business as usual after this.
167 check_after_early_exit = false;
169 // perform spellcheck (default case)
175 void GuiSpellchecker::accept()
181 void GuiSpellchecker::add()
187 void GuiSpellchecker::ignore()
193 void GuiSpellchecker::replace()
195 replace(qstring_to_ucs4(replaceCO->currentText()));
199 void GuiSpellchecker::partialUpdate(int state)
202 case SPELL_PROGRESSED:
203 spellcheckPR->setValue(getProgress());
206 case SPELL_FOUND_WORD: {
207 wordED->setText(toqstr(getWord()));
208 suggestionsLW->clear();
211 while (!(w = getSuggestion()).empty())
212 suggestionsLW->addItem(toqstr(w));
214 if (suggestionsLW->count() == 0)
215 suggestionChanged(new QListWidgetItem(wordED->text()));
217 suggestionChanged(suggestionsLW->item(0));
219 suggestionsLW->setCurrentRow(0);
226 static SpellBase * getSpeller(BufferParams const & bp)
228 string lang = (lyxrc.isp_use_alt_lang)
230 : bp.language->code();
232 #if defined(USE_ASPELL)
233 if (lyxrc.use_spell_lib)
234 return new ASpell(bp, lang);
235 #elif defined(USE_PSPELL)
236 if (lyxrc.use_spell_lib)
237 return new PSpell(bp, lang);
240 #if defined(USE_ISPELL)
241 lang = lyxrc.isp_use_alt_lang ?
242 lyxrc.isp_alt_lang : bp.language->lang();
244 return new ISpell(bp, lang);
246 return new SpellBase;
251 bool GuiSpellchecker::initialiseParams(std::string const &)
253 LYXERR(Debug::GUI) << "Spellchecker::initialiseParams" << endl;
255 speller_ = getSpeller(buffer().params());
259 // reset values to initial
264 bool const success = speller_->error().empty();
267 Alert::error(_("Spellchecker error"),
268 _("The spellchecker could not be started\n")
269 + speller_->error());
278 void GuiSpellchecker::clearParams()
280 LYXERR(Debug::GUI) << "Spellchecker::clearParams" << endl;
286 static bool isLetter(DocIterator const & dit)
288 return dit.inTexted()
289 && dit.inset().allowSpellCheck()
290 && dit.pos() != dit.lastpos()
291 && (dit.paragraph().isLetter(dit.pos())
292 // We want to pass the ' and escape chars to ispell
293 || contains(from_utf8(lyxrc.isp_esc_chars + '\''),
294 dit.paragraph().getChar(dit.pos())))
295 && !dit.paragraph().isDeleted(dit.pos());
299 static WordLangTuple nextWord(Cursor & cur, ptrdiff_t & progress)
301 BufferParams const & bp = cur.bv().buffer().params();
303 bool ignoreword = false;
308 while (cur.depth()) {
315 lang_code = cur.paragraph().getFontSettings(bp, cur.pos()).language()->code();
317 // Insets like optional hyphens and ligature
318 // break are part of a word.
319 if (!cur.paragraph().isInset(cur.pos())) {
320 char_type const c = cur.paragraph().getChar(cur.pos());
325 } else { // !isLetter(cur)
327 if (!word.empty() && !ignoreword) {
329 return WordLangTuple(word, lang_code);
338 return WordLangTuple(docstring(), string());
342 void GuiSpellchecker::check()
344 LYXERR(Debug::GUI) << "Check the spelling of a word" << endl;
346 SpellBase::Result res = SpellBase::OK;
348 Cursor cur = bufferview()->cursor();
349 while (cur && cur.pos() && isLetter(cur))
354 DocIterator it = DocIterator(buffer().inset());
355 for (start = 0; it != cur; it.forwardPos())
358 for (total = start; it; it.forwardPos())
363 while (res == SpellBase::OK || res == SpellBase::IGNORED_WORD) {
364 word_ = nextWord(cur, start);
367 if (getWord().empty()) {
375 // Update slider if and only if value has changed
376 float progress = total ? float(start)/total : 1;
377 newvalue_ = int(100.0 * progress);
378 if (newvalue_!= oldval_) {
379 LYXERR(Debug::GUI) << "Updating spell progress." << endl;
382 partialUpdate(SPELL_PROGRESSED);
385 // speller might be dead ...
389 res = speller_->check(word_);
391 // ... or it might just be reporting an error
396 LYXERR(Debug::GUI) << "Found word \"" << to_utf8(getWord()) << "\"" << endl;
398 int const size = cur.selEnd().pos() - cur.selBegin().pos();
400 bufferview()->putSelectionAt(cur, size, false);
401 // FIXME: if we used a lfun like in find/replace, dispatch would do
403 // FIXME: this Controller is very badly designed...
404 bufferview()->processUpdateFlags(Update::Force | Update::FitCursor);
407 if (res != SpellBase::OK && res != SpellBase::IGNORED_WORD) {
408 LYXERR(Debug::GUI) << "Found a word needing checking." << endl;
409 partialUpdate(SPELL_FOUND_WORD);
414 bool GuiSpellchecker::checkAlive()
416 if (speller_->alive() && speller_->error().empty())
420 if (speller_->error().empty())
421 message = _("The spellchecker has died for some reason.\n"
422 "Maybe it has been killed.");
424 message = _("The spellchecker has failed.\n") + speller_->error();
428 Alert::error(_("The spellchecker has failed"), message);
433 void GuiSpellchecker::showSummary()
435 if (!checkAlive() || count_ == 0) {
442 message = bformat(_("%1$d words checked."), count_);
444 message = _("One word checked.");
447 Alert::information(_("Spelling check completed"), message);
451 void GuiSpellchecker::replace(docstring const & replacement)
453 LYXERR(Debug::GUI) << "GuiSpellchecker::replace("
454 << to_utf8(replacement) << ")" << std::endl;
455 cap::replaceSelectionWithString(bufferview()->cursor(), replacement, true);
456 buffer().markDirty();
457 // If we used an LFUN, we would not need that
458 bufferview()->processUpdateFlags(Update::Force | Update::FitCursor);
465 void GuiSpellchecker::replaceAll(docstring const & replacement)
468 replace(replacement);
472 void GuiSpellchecker::insert()
474 speller_->insert(word_);
479 docstring GuiSpellchecker::getSuggestion() const
481 return speller_->nextMiss();
485 docstring GuiSpellchecker::getWord() const
491 void GuiSpellchecker::ignoreAll()
493 speller_->accept(word_);
498 Dialog * createGuiSpellchecker(LyXView & lv) { return new GuiSpellchecker(lv); }
500 } // namespace frontend
503 #include "GuiSpellchecker_moc.cpp"