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