]> git.lyx.org Git - lyx.git/blob - src/frontends/controllers/ControlSpellchecker.C
fix crash due to invalidated iterator
[lyx.git] / src / frontends / controllers / ControlSpellchecker.C
1 /**
2  * \file ControlSpellchecker.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Edwin Leuven
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "ControlSpellchecker.h"
14
15 #include "buffer.h"
16 #include "bufferparams.h"
17 #include "BufferView.h"
18 #include "cursor.h"
19 #include "CutAndPaste.h"
20 #include "debug.h"
21 #include "gettext.h"
22 #include "language.h"
23 #include "lyxrc.h"
24 #include "paragraph.h"
25
26 #if defined(USE_ASPELL)
27 # include "aspell_local.h"
28 #elif defined(USE_PSPELL)
29 # include "pspell.h"
30 #endif
31
32 #if defined(USE_ISPELL)
33 # include "ispell.h"
34 #else
35 # include "SpellBase.h"
36 #endif
37
38 #include "support/textutils.h"
39 #include "support/convert.h"
40
41 #include "frontends/Alert.h"
42
43 using std::advance;
44 using std::distance;
45 using std::endl;
46 using std::string;
47
48 namespace lyx {
49
50 using support::bformat;
51 using support::contains;
52
53 namespace frontend {
54
55
56 ControlSpellchecker::ControlSpellchecker(Dialog & parent)
57         : Dialog::Controller(parent), exitEarly_(false),
58           oldval_(0), newvalue_(0), count_(0)
59 {}
60
61
62 ControlSpellchecker::~ControlSpellchecker()
63 {}
64
65
66 namespace {
67
68 SpellBase * getSpeller(BufferParams const & bp)
69 {
70         string lang = (lyxrc.isp_use_alt_lang)
71                       ? lyxrc.isp_alt_lang
72                       : bp.language->code();
73
74 #if defined(USE_ASPELL)
75         if (lyxrc.use_spell_lib)
76                 return new ASpell(bp, lang);
77 #elif defined(USE_PSPELL)
78         if (lyxrc.use_spell_lib)
79                 return new PSpell(bp, lang);
80 #endif
81
82 #if defined(USE_ISPELL)
83         lang = (lyxrc.isp_use_alt_lang) ?
84                 lyxrc.isp_alt_lang : bp.language->lang();
85
86         return new ISpell(bp, lang);
87 #else
88         return new SpellBase;
89 #endif
90 }
91
92 } // namespace anon
93
94
95 bool ControlSpellchecker::initialiseParams(std::string const &)
96 {
97         lyxerr[Debug::GUI] << "Spellchecker::initialiseParams" << endl;
98
99         speller_.reset(getSpeller(kernel().buffer().params()));
100         if (!speller_.get())
101                 return false;
102
103         // reset values to initial
104         oldval_ = 0;
105         newvalue_ = 0;
106         count_ = 0;
107
108         bool const success = speller_->error().empty();
109
110         if (!success) {
111                 Alert::error(_("Spellchecker error"),
112                              _("The spellchecker could not be started\n")
113                              + speller_->error());
114                 speller_.reset(0);
115         }
116
117         return success;
118 }
119
120
121 void ControlSpellchecker::clearParams()
122 {
123         lyxerr[Debug::GUI] << "Spellchecker::clearParams" << endl;
124         speller_.reset(0);
125 }
126
127
128 namespace {
129
130 bool isLetter(DocIterator const & cur)
131 {
132         return cur.inTexted()
133                 && cur.inset().allowSpellCheck()
134                 && cur.pos() != cur.lastpos()
135                 && (cur.paragraph().isLetter(cur.pos())
136                     // We want to pass the ' and escape chars to ispell
137                     || contains(lyxrc.isp_esc_chars + '\'',
138                                 cur.paragraph().getChar(cur.pos())))
139                 && !isDeletedText(cur.paragraph(), cur.pos());
140 }
141
142
143 WordLangTuple nextWord(DocIterator & cur, ptrdiff_t & progress,
144         BufferParams & bp)
145 {
146         bool inword = false;
147         bool ignoreword = false;
148         string word, lang_code;
149
150         while (cur.depth()) {
151                 if (isLetter(cur)) {
152                         if (!inword) {
153                                 inword = true;
154                                 ignoreword = false;
155                                 word.clear();
156                                 lang_code = cur.paragraph().getFontSettings(bp, cur.pos()).language()->code();
157                         }
158                         // Insets like optional hyphens and ligature
159                         // break are part of a word.
160                         if (!cur.paragraph().isInset(cur.pos())) {
161                                 Paragraph::value_type const c =
162                                         cur.paragraph().getChar(cur.pos());
163                                 word += c;
164                                 if (IsDigit(c))
165                                         ignoreword = true;
166                         }
167                 } else { // !isLetter(cur)
168                         if (inword)
169                                 if (!word.empty() && !ignoreword)
170                                         return WordLangTuple(word, lang_code);
171                                 else
172                                         inword = false;
173                 }
174
175                 cur.forwardPos();
176                 ++progress;
177         }
178
179         return WordLangTuple(string(), string());
180 }
181
182 } // namespace anon
183
184
185
186 void ControlSpellchecker::check()
187 {
188         lyxerr[Debug::GUI] << "Check the spelling of a word" << endl;
189
190         SpellBase::Result res = SpellBase::OK;
191
192         DocIterator cur = kernel().bufferview()->cursor();
193         while (cur && cur.pos() && isLetter(cur)) {
194                 cur.backwardPos();
195         }
196
197         ptrdiff_t start = 0, total = 0;
198         DocIterator it = DocIterator(kernel().buffer().inset());
199         for (start = 0; it != cur; it.forwardPos())
200                 ++start;
201
202         for (total = start; it; it.forwardPos())
203                 ++total;
204
205         BufferParams & bufferparams = kernel().buffer().params();
206         exitEarly_ = false;
207
208         while (res == SpellBase::OK || res == SpellBase::IGNORED_WORD) {
209                 word_ = nextWord(cur, start, bufferparams);
210
211                 // end of document
212                 if (getWord().empty()) {
213                         showSummary();
214                         exitEarly_ = true;
215                         return;
216                 }
217
218                 ++count_;
219
220                 // Update slider if and only if value has changed
221                 float progress = total ? float(start)/total : 1;
222                 newvalue_ = int(100.0 * progress);
223                 if (newvalue_!= oldval_) {
224                         lyxerr[Debug::GUI] << "Updating spell progress." << endl;
225                         oldval_ = newvalue_;
226                         // set progress bar
227                         dialog().view().partialUpdate(SPELL_PROGRESSED);
228                 }
229
230                 // speller might be dead ...
231                 if (!checkAlive())
232                         return;
233
234                 res = speller_->check(word_);
235
236                 // ... or it might just be reporting an error
237                 if (!checkAlive())
238                         return;
239         }
240
241         lyxerr[Debug::GUI] << "Found word \"" << getWord() << "\"" << endl;
242
243         int const size = getWord().size();
244         cur.pos() -= size;
245         kernel().bufferview()->putSelectionAt(cur, size, false);
246         // if we used a lfun like in find/replace, dispatch would do
247         // that for us
248         kernel().bufferview()->update();
249
250         // set suggestions
251         if (res != SpellBase::OK && res != SpellBase::IGNORED_WORD) {
252                 lyxerr[Debug::GUI] << "Found a word needing checking." << endl;
253                 dialog().view().partialUpdate(SPELL_FOUND_WORD);
254         }
255 }
256
257
258 bool ControlSpellchecker::checkAlive()
259 {
260         if (speller_->alive() && speller_->error().empty())
261                 return true;
262
263         string message;
264         if (speller_->error().empty())
265                 message = _("The spellchecker has died for some reason.\n"
266                             "Maybe it has been killed.");
267         else
268                 message = _("The spellchecker has failed.\n") 
269                         + speller_->error();
270
271         dialog().CancelButton();
272
273         Alert::error(_("The spellchecker has failed"), message);
274         return false;
275 }
276
277
278 void ControlSpellchecker::showSummary()
279 {
280         if (!checkAlive() || count_ == 0) {
281                 dialog().CancelButton();
282                 return;
283         }
284
285         string message;
286         if (count_ != 1)
287                 message = bformat(_("%1$d words checked."), count_);
288         else
289                 message = _("One word checked.");
290
291         dialog().CancelButton();
292         Alert::information(_("Spelling check completed"), message);
293 }
294
295
296 void ControlSpellchecker::replace(string const & replacement)
297 {
298         lyxerr << "ControlSpellchecker::replace("
299                << replacement << ")" << std::endl;
300         BufferView & bufferview = *kernel().bufferview();
301         cap::replaceWord(bufferview.cursor(), replacement);
302         kernel().buffer().markDirty();
303         bufferview.update();
304         // fix up the count
305         --count_;
306         check();
307 }
308
309
310 void ControlSpellchecker::replaceAll(string const & replacement)
311 {
312         // TODO: add to list
313         replace(replacement);
314 }
315
316
317 void ControlSpellchecker::insert()
318 {
319         speller_->insert(word_);
320         check();
321 }
322
323
324 string const ControlSpellchecker::getSuggestion() const
325 {
326         return speller_->nextMiss();
327 }
328
329
330 string const ControlSpellchecker::getWord() const
331 {
332         return word_.word();
333 }
334
335
336 void ControlSpellchecker::ignoreAll()
337 {
338         speller_->accept(word_);
339         check();
340 }
341
342 } // namespace frontend
343 } // namespace lyx