]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
Look for mathed xpms. Doesn't do anything yet due to lack of workable XPMs
[lyx.git] / src / lyx_cb.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *          Copyright 1995 Matthias Ettrich,
7  *          Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include "lyx_cb.h"
14 #include "lyx_main.h"
15 #include "buffer.h"
16 #include "bufferlist.h"
17 #include "bufferview_funcs.h"
18 #include "debug.h"
19 #include "lastfiles.h"
20 #include "lyxrc.h"
21 #include "lyxtext.h"
22 #include "gettext.h"
23 #include "BufferView.h"
24
25 #include "insets/insetlabel.h"
26
27 #include "frontends/lyx_gui.h"
28 #include "frontends/LyXView.h"
29 #include "frontends/Alert.h"
30 #include "frontends/FileDialog.h"
31
32 #include "support/FileInfo.h"
33 #include "support/filetools.h"
34 #include "support/path.h"
35 #include "support/systemcall.h"
36 #include "support/lstrings.h"
37
38 #include <fstream>
39 #include <algorithm>
40 #include <utility>
41 #include <iostream>
42
43 using std::vector;
44 using std::ifstream;
45 using std::copy;
46 using std::endl;
47 using std::ios;
48 using std::back_inserter;
49 using std::istream_iterator;
50 using std::pair;
51 using std::make_pair;
52
53 extern BufferList bufferlist;
54 // this should be static, but I need it in buffer.C
55 bool quitting;  // flag, that we are quitting the program
56
57
58 void ShowMessage(Buffer const * buf,
59                  string const & msg1,
60                  string const & msg2,
61                  string const & msg3)
62 {
63         if (lyxrc.use_gui
64             && buf && buf->getUser() && buf->getUser()->owner()) {
65                         string const str = msg1 + ' ' + msg2 + ' ' + msg3;
66                         buf->getUser()->owner()->message(str);
67         } else
68                 lyxerr << msg1 << msg2 << msg3 << endl;
69 }
70
71
72 //
73 // Menu callbacks
74 //
75
76 //
77 // File menu
78 //
79 // should be moved to lyxfunc.C
80 bool MenuWrite(BufferView * bv, Buffer * buffer)
81 {
82         if (!buffer->save()) {
83                 if (Alert::askQuestion(_("Save failed. Rename and try again?"),
84                                 MakeDisplayPath(buffer->fileName(), 50),
85                                 _("(If not, document is not saved.)"))) {
86                         return WriteAs(bv, buffer);
87                 }
88                 return false;
89         } else
90                 lastfiles->newFile(buffer->fileName());
91         return true;
92 }
93
94
95
96 // should be moved to BufferView.C
97 // Half of this func should be in LyXView, the rest in BufferView.
98 bool WriteAs(BufferView * bv, Buffer * buffer, string const & filename)
99 {
100         string fname = buffer->fileName();
101         string const oldname = fname;
102
103         if (filename.empty()) {
104
105                 FileDialog fileDlg(bv->owner(),
106                                    _("Choose a filename to save document as"),
107                         LFUN_WRITEAS,
108                         make_pair(string(_("Documents|#o#O")),
109                                   string(lyxrc.document_path)),
110                         make_pair(string(_("Templates|#T#t")),
111                                   string(lyxrc.template_path)));
112
113                 if (!IsLyXFilename(fname))
114                         fname += ".lyx";
115
116                 FileDialog::Result result =
117                         fileDlg.Select(OnlyPath(fname),
118                                        _("*.lyx|LyX Documents (*.lyx)"),
119                                        OnlyFilename(fname));
120
121                 if (result.first == FileDialog::Later)
122                         return false;
123
124                 fname = result.second;
125
126                 if (fname.empty())
127                         return false;
128
129                 // Make sure the absolute filename ends with appropriate suffix
130                 fname = MakeAbsPath(fname);
131                 if (!IsLyXFilename(fname))
132                         fname += ".lyx";
133         } else
134                 fname = filename;
135
136         // Same name as we have already?
137         if (!buffer->isUnnamed() && fname == oldname) {
138                 if (!Alert::askQuestion(_("Same name as document already has:"),
139                                  MakeDisplayPath(fname, 50),
140                                  _("Save anyway?")))
141                         return false;
142                 // Falls through to name change and save
143         }
144         // No, but do we have another file with this name open?
145         else if (!buffer->isUnnamed() && bufferlist.exists(fname)) {
146                 if (Alert::askQuestion(_("Another document with same name open!"),
147                                 MakeDisplayPath(fname, 50),
148                                 _("Replace with current document?")))
149                         {
150                                 bufferlist.close(bufferlist.getBuffer(fname));
151
152                                 // Ok, change the name of the buffer, but don't save!
153                                 buffer->setFileName(fname);
154                                 buffer->markDirty();
155
156                                 ShowMessage(buffer, _("Document renamed to '"),
157                                                 MakeDisplayPath(fname), _("', but not saved..."));
158                 }
159                 return false;
160         } // Check whether the file exists
161         else {
162                 FileInfo const myfile(fname);
163                 if (myfile.isOK() && !Alert::askQuestion(_("Document already exists:"),
164                                                   MakeDisplayPath(fname, 50),
165                                                   _("Replace file?")))
166                         return false;
167         }
168
169         // Ok, change the name of the buffer
170         buffer->setFileName(fname);
171         buffer->markDirty();
172         bool unnamed = buffer->isUnnamed();
173         buffer->setUnnamed(false);
174
175         if (!MenuWrite(bv, buffer)) {
176             buffer->setFileName(oldname);
177             buffer->setUnnamed(unnamed);
178             ShowMessage(buffer, _("Document could not be saved!"),
179                         _("Holding the old name."), MakeDisplayPath(oldname));
180             return false;
181         }
182         // now remove the oldname autosave file if existant!
183         removeAutosaveFile(oldname);
184         return true;
185 }
186
187
188 int MenuRunChktex(Buffer * buffer)
189 {
190         int ret;
191
192         if (buffer->isSGML()) {
193                 Alert::alert(_("Chktex does not work with SGML derived documents."));
194                 return 0;
195         } else
196                 ret = buffer->runChktex();
197
198         if (ret >= 0) {
199                 string s;
200                 string t;
201                 if (ret == 0) {
202                         s = _("No warnings found.");
203                 } else if (ret == 1) {
204                         s = _("One warning found.");
205                         t = _("Use `Navigate->Error' to find it.");
206                 } else {
207                         s += tostr(ret);
208                         s += _(" warnings found.");
209                         t = _("Use `Navigate->Error' to find them.");
210                 }
211                 Alert::alert(_("Chktex run successfully"), s, t);
212         } else {
213                 Alert::alert(_("Error!"), _("It seems chktex does not work."));
214         }
215         return ret;
216 }
217
218
219 void QuitLyX()
220 {
221         lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
222
223         if (lyxrc.use_gui) {
224                 if (!bufferlist.qwriteAll())
225                         return;
226
227                 lastfiles->writeFile(lyxrc.lastfiles);
228         }
229
230         // Set a flag that we do quitting from the program,
231         // so no refreshes are necessary.
232         quitting = true;
233
234         // close buffers first
235         bufferlist.closeAll();
236
237         // do any other cleanup procedures now
238         lyxerr[Debug::INFO] << "Deleting tmp dir " << system_tempdir << endl;
239
240         DestroyLyXTmpDir(system_tempdir);
241
242         lyx_gui::exit();
243 }
244
245
246
247 void AutoSave(BufferView * bv)
248         // should probably be moved into BufferList (Lgb)
249         // Perfect target for a thread...
250 {
251         if (!bv->available())
252                 return;
253
254         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
255                 // We don't save now, but we'll try again later
256                 bv->owner()->resetAutosaveTimer();
257                 return;
258         }
259
260         bv->owner()->message(_("Autosaving current document..."));
261
262         // create autosave filename
263         string fname =  bv->buffer()->filePath();
264         fname += "#";
265         fname += OnlyFilename(bv->buffer()->fileName());
266         fname += "#";
267
268         // tmp_ret will be located (usually) in /tmp
269         // will that be a problem?
270         pid_t const pid = fork(); // If you want to debug the autosave
271         // you should set pid to -1, and comment out the
272         // fork.
273         if (pid == 0 || pid == -1) {
274                 // pid = -1 signifies that lyx was unable
275                 // to fork. But we will do the save
276                 // anyway.
277                 bool failed = false;
278
279                 string const tmp_ret = lyx::tempName(string(), "lyxauto");
280                 if (!tmp_ret.empty()) {
281                         bv->buffer()->writeFile(tmp_ret);
282                         // assume successful write of tmp_ret
283                         if (!lyx::rename(tmp_ret, fname)) {
284                                 failed = true;
285                                 // most likely couldn't move between filesystems
286                                 // unless write of tmp_ret failed
287                                 // so remove tmp file (if it exists)
288                                 lyx::unlink(tmp_ret);
289                         }
290                 } else {
291                         failed = true;
292                 }
293
294                 if (failed) {
295                         // failed to write/rename tmp_ret so try writing direct
296                         if (!bv->buffer()->writeFile(fname)) {
297                                 // It is dangerous to do this in the child,
298                                 // but safe in the parent, so...
299                                 if (pid == -1)
300                                         bv->owner()->message(_("Autosave failed!"));
301                         }
302                 }
303                 if (pid == 0) { // we are the child so...
304                         _exit(0);
305                 }
306         }
307
308         bv->buffer()->markBakClean();
309         bv->owner()->resetAutosaveTimer();
310 }
311
312
313 //
314 // Copyright CHT Software Service GmbH
315 // Uwe C. Schroeder
316 //
317 // create new file with template
318 // SERVERCMD !
319 //
320 Buffer * NewFile(string const & filename)
321 {
322         // Split argument by :
323         string name;
324         string tmpname = split(filename, name, ':');
325 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
326         if (name.length() == 1
327             && isalpha(static_cast<unsigned char>(name[0]))
328             && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
329                 name += ':';
330                 name += token(tmpname, ':', 0);
331                 tmpname = split(tmpname, ':');
332         }
333 #endif
334         lyxerr[Debug::INFO] << "Arg is " << filename
335                             << "\nName is " << name
336                             << "\nTemplate is " << tmpname << endl;
337
338         // find a free buffer
339         Buffer * tmpbuf = bufferlist.newFile(name, tmpname);
340         if (tmpbuf)
341                 lastfiles->newFile(tmpbuf->fileName());
342         return tmpbuf;
343 }
344
345
346 // Insert ascii file (if filename is empty, prompt for one)
347 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
348 {
349         if (!bv->available())
350                 return;
351
352         string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
353         if (tmpstr.empty())
354                 return;
355
356         // insert the string
357         bv->hideCursor();
358
359         // clear the selection
360         bool flag = (bv->text == bv->getLyXText());
361         if (flag)
362                 bv->beforeChange(bv->text);
363         if (!asParagraph)
364                 bv->getLyXText()->insertStringAsLines(bv, tmpstr);
365         else
366                 bv->getLyXText()->insertStringAsParagraphs(bv, tmpstr);
367         if (flag)
368                 bv->update(bv->text,
369                            BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
370 }
371
372
373 // Insert ascii file (if filename is empty, prompt for one)
374 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
375 {
376         string fname = f;
377
378         if (fname.empty()) {
379                 FileDialog fileDlg(bv->owner(), _("Select file to insert"),
380                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
381
382                 FileDialog::Result result = fileDlg.Select(bv->owner()->buffer()->filePath());
383
384                 if (result.first == FileDialog::Later)
385                         return string();
386
387                 fname = result.second;
388
389                 if (fname.empty())
390                         return string();
391         }
392
393         FileInfo fi(fname);
394
395         if (!fi.readable()) {
396                 Alert::err_alert(_("Error! Specified file is unreadable: "),
397                              MakeDisplayPath(fname, 50));
398                 return string();
399         }
400
401         ifstream ifs(fname.c_str());
402         if (!ifs) {
403                 Alert::err_alert(_("Error! Cannot open specified file: "),
404                              MakeDisplayPath(fname, 50));
405                 return string();
406         }
407
408         ifs.unsetf(ios::skipws);
409         istream_iterator<char> ii(ifs);
410         istream_iterator<char> end;
411 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
412         // We use this until the compilers get better...
413         vector<char> tmp;
414         copy(ii, end, back_inserter(tmp));
415         string const tmpstr(tmp.begin(), tmp.end());
416 #else
417         // This is what we want to use and what we will use once the
418         // compilers get good enough.
419         //string tmpstr(ii, end); // yet a reason for using std::string
420         // alternate approach to get the file into a string:
421         string tmpstr;
422         copy(ii, end, back_inserter(tmpstr));
423 #endif
424
425         return tmpstr;
426 }
427
428
429 void MenuInsertLabel(BufferView * bv, string const & arg)
430 {
431         string label = arg;
432         bv->owner()->prohibitInput();
433         if (label.empty()) {
434                 Paragraph * par = bv->getLyXText()->cursor.par();
435                 LyXLayout_ptr layout = par->layout();
436                 if (layout->latextype == LATEX_PARAGRAPH && par->previous()) {
437                         Paragraph * par2 = par->previous();
438
439                         LyXLayout_ptr const & layout2 = par2->layout();
440
441                         if (layout2->latextype != LATEX_PARAGRAPH) {
442                                 par = par2;
443                                 layout = layout2;
444                         }
445                 }
446                 string text = layout->latexname().substr(0, 3);
447                 if (layout->latexname() == "theorem")
448                         text = "thm"; // Create a correct prefix for prettyref
449
450                 text += ":";
451                 if (layout->latextype == LATEX_PARAGRAPH ||
452                     lyxrc.label_init_length < 0)
453                         text.erase();
454                 string par_text = par->asString(bv->buffer(), false);
455                 for (int i = 0; i < lyxrc.label_init_length; ++i) {
456                         if (par_text.empty())
457                                 break;
458                         string head;
459                         par_text = split(par_text, head, ' ');
460                         if (i > 0)
461                                 text += '-'; // Is it legal to use spaces in
462                                              // labels ?
463                         text += head;
464                 }
465
466                 pair<bool, string> result =
467                         Alert::askForText(_("Enter new label to insert:"), text);
468                 if (result.first) {
469                         label = trim(result.second);
470                 }
471         }
472         if (!label.empty()) {
473                 InsetCommandParams p("label", label);
474                 InsetLabel * inset = new InsetLabel(p);
475                 bv->insertInset(inset);
476         }
477         bv->owner()->allowInput();
478 }
479
480
481 // This function runs "configure" and then rereads lyx.defaults to
482 // reconfigure the automatic settings.
483 void Reconfigure(BufferView * bv)
484 {
485         bv->owner()->message(_("Running configure..."));
486
487         // Run configure in user lyx directory
488         Path p(user_lyxdir);
489         Systemcall one;
490         one.startscript(Systemcall::Wait,
491                         AddName(system_lyxdir, "configure"));
492         p.pop();
493         bv->owner()->message(_("Reloading configuration..."));
494         lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
495         Alert::alert(_("The system has been reconfigured."),
496                    _("You need to restart LyX to make use of any"),
497                    _("updated document class specifications."));
498 }