]> git.lyx.org Git - lyx.git/blob - src/ispell.C
hopefully fix tex2lyx linking.
[lyx.git] / src / ispell.C
1 /**
2  * \file ispell.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author unknown
7  * \author Angus Leeming
8  * \author John Levon
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "ispell.h"
16
17 #include "bufferparams.h"
18 #include "debug.h"
19 #include "encoding.h"
20 #include "gettext.h"
21 #include "language.h"
22 #include "lyxrc.h"
23 #include "WordLangTuple.h"
24
25 #include "support/forkedcall.h"
26
27 // HP-UX 11.x doesn't have this header
28 #ifdef HAVE_SYS_SELECT_H
29 # include <sys/select.h>
30 #endif
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
33 #endif
34
35
36 namespace lyx {
37
38 using boost::shared_ptr;
39
40 #ifndef CXX_GLOBAL_CSTD
41 using std::strcpy;
42 using std::strlen;
43 using std::strpbrk;
44 #endif
45
46 using std::endl;
47 using std::max;
48 using std::string;
49
50
51 namespace {
52
53 class LaunchIspell : public support::ForkedProcess {
54         typedef support::ForkedProcess ForkedProcess;
55 public:
56         ///
57         LaunchIspell(BufferParams const & p, string const & l,
58                      int * in, int * out, int * err)
59                 : params(p), lang(l), pipein(in), pipeout(out), pipeerr(err) {}
60         ///
61         virtual shared_ptr<ForkedProcess> clone() const {
62                 return shared_ptr<ForkedProcess>(new LaunchIspell(*this));
63         }
64         ///
65         int start();
66 private:
67         ///
68         virtual int generateChild();
69
70         ///
71         BufferParams const & params;
72         string const & lang;
73         int * const pipein;
74         int * const pipeout;
75         int * const pipeerr;
76 };
77
78
79 int LaunchIspell::start()
80 {
81         command_ = lyxrc.isp_command;
82         return run(DontWait);
83 }
84
85
86 int LaunchIspell::generateChild()
87 {
88         pid_t isp_pid = fork();
89
90         if (isp_pid != 0) {
91                 // failed (-1) or parent process (>0)
92                 return isp_pid;
93         }
94
95         // child process
96         dup2(pipein[0], STDIN_FILENO);
97         dup2(pipeout[1], STDOUT_FILENO);
98         dup2(pipeerr[1], STDERR_FILENO);
99         close(pipein[0]);
100         close(pipein[1]);
101         close(pipeout[0]);
102         close(pipeout[1]);
103         close(pipeerr[0]);
104         close(pipeerr[1]);
105
106         char * argv[14];
107         int argc = 0;
108
109         char * tmp = new char[lyxrc.isp_command.length() + 1];
110         lyxrc.isp_command.copy(tmp, lyxrc.isp_command.length());
111         tmp[lyxrc.isp_command.length()] = '\0';
112         argv[argc++] = tmp;
113         tmp = new char[3];
114         string("-a").copy(tmp, 2); tmp[2] = '\0'; // pipe mode
115         argv[argc++] = tmp;
116
117         if (lang != "default") {
118                 tmp = new char[3];
119                 string("-d").copy(tmp, 2); tmp[2] = '\0'; // Dictionary file
120                 argv[argc++] = tmp;
121                 tmp = new char[lang.length() + 1];
122                 lang.copy(tmp, lang.length()); tmp[lang.length()] = '\0';
123                 argv[argc++] = tmp;
124         }
125
126         if (lyxrc.isp_accept_compound) {
127                 // Consider run-together words as legal compounds
128                 tmp = new char[3];
129                 string("-C").copy(tmp, 2); tmp[2] = '\0';
130                 argv[argc++] = tmp;
131         } else {
132                 // Report run-together words with
133                 // missing blanks as errors
134                 tmp = new char[3];
135                 string("-B").copy(tmp, 2); tmp[2] = '\0';
136                 argv[argc++] = tmp;
137         }
138         if (lyxrc.isp_use_esc_chars) {
139                 // Specify additional characters that
140                 // can be part of a word
141                 tmp = new char[3];
142                 string("-w").copy(tmp, 2); tmp[2] = '\0';
143                 argv[argc++] = tmp;
144                 // Put the escape chars in ""s
145                 string tms = '"' + lyxrc.isp_esc_chars + '"';
146                 tmp = new char[tms.length() + 1];
147                 tms.copy(tmp, tms.length()); tmp[tms.length()] = '\0';
148                 argv[argc++] = tmp;
149         }
150         if (lyxrc.isp_use_pers_dict) {
151                 // Specify an alternate personal dictionary
152                 tmp = new char[3];
153                 string("-p").copy(tmp, 2);
154                 tmp[2]= '\0';
155                 argv[argc++] = tmp;
156                 tmp = new char[lyxrc.isp_pers_dict.length() + 1];
157                 lyxrc.isp_pers_dict.copy(tmp, lyxrc.isp_pers_dict.length());
158                 tmp[lyxrc.isp_pers_dict.length()] = '\0';
159                 argv[argc++] = tmp;
160         }
161         if (lyxrc.isp_use_input_encoding &&
162             params.inputenc != "default") {
163                 string enc = (params.inputenc == "auto")
164                         ? params.language->encoding()->latexName()
165                         : params.inputenc;
166                 size_t const n = enc.length();
167                 tmp = new char[3];
168                 string("-T").copy(tmp, 2);
169                 tmp[2] = '\0';
170                 argv[argc++] = tmp; // Input encoding
171                 tmp = new char[n + 1];
172                 enc.copy(tmp, n);
173                 tmp[n] = '\0';
174                 argv[argc++] = tmp;
175         }
176
177         argv[argc++] = 0;
178
179         execvp(argv[0], const_cast<char * const *>(argv));
180
181         // free the memory used by string::copy in the
182         // setup of argv
183         for (int i = 0; i < argc - 1; ++i)
184                 delete[] argv[i];
185
186         lyxerr << "LyX: Failed to start ispell!" << endl;
187         _exit(0);
188 }
189
190
191 } // namespace anon
192
193
194 ISpell::ISpell(BufferParams const & params, string const & lang)
195         : in(0), out(0), inerr(0), str(0)
196 {
197         lyxerr[Debug::GUI] << "Created ispell" << endl;
198
199         // static due to the setvbuf. Ugly.
200         static char o_buf[BUFSIZ];
201
202         // We need to throw an exception not do this
203         pipein[0] = pipein[1] = pipeout[0] = pipeout[1]
204                 = pipeerr[0] = pipeerr[1] = -1;
205
206         // This is what happens when goto gets banned.
207
208         if (pipe(pipein) == -1) {
209                 error_ = _("Can't create pipe for spellchecker.");
210                 return;
211         }
212
213         if (pipe(pipeout) == -1) {
214                 close(pipein[0]);
215                 close(pipein[1]);
216                 error_ = _("Can't create pipe for spellchecker.");
217                 return;
218         }
219
220         if (pipe(pipeerr) == -1) {
221                 close(pipein[0]);
222                 close(pipein[1]);
223                 close(pipeout[0]);
224                 close(pipeout[1]);
225                 error_ = _("Can't create pipe for spellchecker.");
226                 return;
227         }
228
229         if ((out = fdopen(pipein[1], "w")) == 0) {
230                 error_ = _("Can't open pipe for spellchecker.");
231                 return;
232         }
233
234         if ((in = fdopen(pipeout[0], "r")) == 0) {
235                 error_ = _("Can't open pipe for spellchecker.");
236                 return;
237         }
238
239         if ((inerr = fdopen(pipeerr[0], "r")) == 0) {
240                 error_ = _("Can't open pipe for spellchecker.");
241                 return;
242         }
243
244         setvbuf(out, o_buf, _IOLBF, BUFSIZ);
245
246         LaunchIspell * li = new LaunchIspell(params, lang, pipein, pipeout, pipeerr);
247         child_.reset(li);
248         if (li->start() == -1) {
249                 error_ = _("Could not create an ispell process.\nYou may not have "
250                                         "the right languages installed.");
251                 child_.reset(0);
252                 return;
253         }
254
255         /* Parent process: Read ispells identification message */
256
257         bool err_read;
258         bool error = select(err_read);
259
260         if (!error) {
261                 if (!err_read) {
262                         // Set terse mode (silently accept correct words)
263                         fputs("!\n", out);
264                         return;
265                 }
266
267                 /* must have read something from stderr */
268                 error_ =from_utf8(buf);
269         } else {
270                 // select returned error
271                 error_ = _("The ispell process returned an error.\nPerhaps "
272                            "it has been configured wrongly ?");
273         }
274
275         close(pipein[0]);
276         close(pipein[1]);
277         close(pipeout[0]);
278         close(pipeout[1]);
279         close(pipeerr[0]);
280         close(pipeerr[1]);
281         child_->kill();
282         child_.reset(0);
283 }
284
285
286 ISpell::~ISpell()
287 {
288         lyxerr[Debug::GUI] << "Killing ispell" << endl;
289
290         if (in)
291                 fclose(in);
292
293         if (inerr)
294                 fclose(inerr);
295
296         if (out) {
297                 fputs("#\n", out); // Save personal dictionary
298
299                 fflush(out);
300                 fclose(out);
301         }
302
303         close(pipein[0]);
304         close(pipein[1]);
305         close(pipeout[0]);
306         close(pipeout[1]);
307         close(pipeerr[0]);
308         close(pipeerr[1]);
309         delete [] str;
310 }
311
312
313 bool ISpell::select(bool & err_read)
314 {
315         fd_set infds;
316         struct timeval tv;
317         int retval = 0;
318         FD_ZERO(&infds);
319         FD_SET(pipeout[0], &infds);
320         FD_SET(pipeerr[0], &infds);
321         tv.tv_sec = 2;
322         tv.tv_usec = 0;
323
324         retval = ::select(SELECT_TYPE_ARG1 (max(pipeout[0], pipeerr[0]) + 1),
325                         SELECT_TYPE_ARG234 (&infds),
326                         0,
327                         0,
328                         SELECT_TYPE_ARG5 (&tv));
329
330         // error
331         if (retval <= 0)
332                 return true;
333
334         if (FD_ISSET(pipeerr[0], &infds)) {
335                 fgets(buf, BUFSIZ, inerr);
336                 err_read = true;
337                 return false;
338         }
339
340         fgets(buf, BUFSIZ, in);
341         err_read = false;
342         return false;
343 }
344
345
346 string const ISpell::nextMiss()
347 {
348         // Well, somebody is a sick fuck.
349
350         if (str == 0 || *(e+1) == '\0')
351                 return "";
352         char * b = e + 2;
353         e = strpbrk(b, ",\n");
354         *e = '\0';
355         if (b)
356                 return b;
357         return "";
358 }
359
360
361 bool ISpell::alive()
362 {
363         return child_.get() && child_->running();
364 }
365
366
367 enum ISpell::Result ISpell::check(WordLangTuple const & word)
368 {
369         // FIXME Please rewrite to use string.
370
371         Result res;
372
373         ::fputs(word.word().c_str(), out);
374         ::fputc('\n', out);
375
376         bool err_read;
377         bool error = select(err_read);
378
379         if (error) {
380                 error_ = _("Could not communicate with the ispell spellchecker process.");
381                 return UNKNOWN_WORD;
382         }
383
384         if (err_read) {
385                 error_ = from_utf8(buf);
386                 return UNKNOWN_WORD;
387         }
388
389         // I think we have to check if ispell is still alive here because
390         // the signal-handler could have disabled blocking on the fd
391         if (!alive())
392                 return UNKNOWN_WORD;
393
394         switch (*buf) {
395         case '*':
396                 res = OK;
397                 break;
398         case '+':
399                 res = ROOT;
400                 break;
401         case '-':
402                 res = COMPOUND_WORD;
403                 break;
404         case '\n':
405                 res = IGNORED_WORD;
406                 break;
407         case '#': // Not found, no near misses and guesses
408                 res = UNKNOWN_WORD;
409                 break;
410         case '?': // Not found, and no near misses, but guesses (guesses are ignored)
411         case '&': // Not found, but we have near misses
412         {
413                 res = SUGGESTED_WORDS;
414                 char * p = strpbrk(buf, ":");
415                 str = new char[strlen(p) + 1];
416                 e   = str;
417                 strcpy(str, p);
418                 break;
419         }
420         default: // This shouldn't happen, but you know Murphy
421                 res = UNKNOWN_WORD;
422         }
423
424         *buf = 0;
425         if (res != IGNORED_WORD) {
426                 /* wait for ispell to finish */
427                 while (*buf!= '\n')
428                         fgets(buf, 255, in);
429         }
430         return res;
431 }
432
433
434 void ISpell::insert(WordLangTuple const & word)
435 {
436         ::fputc('*', out); // Insert word in personal dictionary
437         ::fputs(word.word().c_str(), out);
438         ::fputc('\n', out);
439 }
440
441
442 void ISpell::accept(WordLangTuple const & word)
443 {
444         ::fputc('@', out); // Accept in this session
445         ::fputs(word.word().c_str(), out);
446         ::fputc('\n', out);
447 }
448
449
450 docstring const ISpell::error()
451 {
452         return error_;
453 }
454
455
456 } // namespace lyx