1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich,
7 * Copyright 1995-2001 The LyX Team.
9 * ====================================================== */
16 #include "bufferlist.h"
17 #include "bufferview_funcs.h"
19 #include "lastfiles.h"
23 #include "BufferView.h"
25 #include "insets/insetlabel.h"
27 #include "frontends/lyx_gui.h"
28 #include "frontends/LyXView.h"
29 #include "frontends/Alert.h"
30 #include "frontends/FileDialog.h"
32 #include "support/FileInfo.h"
33 #include "support/filetools.h"
34 #include "support/forkedcall.h"
35 #include "support/path.h"
36 #include "support/systemcall.h"
37 #include "support/lstrings.h"
39 #include "support/BoostFormat.h"
51 using std::back_inserter;
52 using std::istream_iterator;
56 extern BufferList bufferlist;
57 // this should be static, but I need it in buffer.C
58 bool quitting; // flag, that we are quitting the program
61 void ShowMessage(Buffer const * buf,
67 && buf && buf->getUser() && buf->getUser()->owner()) {
68 string const str = msg1 + ' ' + msg2 + ' ' + msg3;
69 buf->getUser()->owner()->message(str);
71 lyxerr << msg1 << msg2 << msg3 << endl;
79 bool MenuWrite(BufferView * bv, Buffer * buffer)
82 lastfiles->newFile(buffer->fileName());
86 // FIXME: we don't tell the user *WHY* the save failed !!
88 string const file = MakeDisplayPath(buffer->fileName(), 30);
91 boost::format fmt(_("The document %1$s could not be saved.\n\nDo you want to rename the document and try again?"));
93 string text = fmt.str();
95 string text = _("The document ");
96 text += file + _(" could not be saved.\n\nDo you want to rename the document and try again?");
98 int const ret = Alert::prompt(_("Rename and save?"),
99 text, 0, 1, _("&Rename"), _("&Cancel"));
102 return WriteAs(bv, buffer);
108 bool WriteAs(BufferView * bv, Buffer * buffer, string const & filename)
110 string fname = buffer->fileName();
111 string const oldname = fname;
113 if (filename.empty()) {
115 FileDialog fileDlg(_("Choose a filename to save document as"),
117 make_pair(string(_("Documents|#o#O")),
118 string(lyxrc.document_path)),
119 make_pair(string(_("Templates|#T#t")),
120 string(lyxrc.template_path)));
122 if (!IsLyXFilename(fname))
125 FileDialog::Result result =
126 fileDlg.save(OnlyPath(fname),
127 _("*.lyx| LyX Documents (*.lyx)"),
128 OnlyFilename(fname));
130 if (result.first == FileDialog::Later)
133 fname = result.second;
138 // Make sure the absolute filename ends with appropriate suffix
139 fname = MakeAbsPath(fname);
140 if (!IsLyXFilename(fname))
145 FileInfo const myfile(fname);
147 string const file = MakeDisplayPath(fname, 30);
150 boost::format fmt(_("The document %1$s already exists.\n\nDo you want to over-write that document?"));
152 string text = fmt.str();
154 string text = _("The document ");
155 text += file + _(" already exists.\n\nDo you want to over-write that document?");
157 int const ret = Alert::prompt(_("Over-write document?"),
158 text, 0, 1, _("&Over-write"), _("&Cancel"));
164 // Ok, change the name of the buffer
165 buffer->setFileName(fname);
167 bool unnamed = buffer->isUnnamed();
168 buffer->setUnnamed(false);
170 if (!MenuWrite(bv, buffer)) {
171 buffer->setFileName(oldname);
172 buffer->setUnnamed(unnamed);
176 removeAutosaveFile(oldname);
183 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
185 if (lyx_gui::use_gui) {
186 if (!bufferlist.quitWriteAll())
189 lastfiles->writeFile(lyxrc.lastfiles);
192 // Set a flag that we do quitting from the program,
193 // so no refreshes are necessary.
196 // close buffers first
197 bufferlist.closeAll();
199 // do any other cleanup procedures now
200 lyxerr[Debug::INFO] << "Deleting tmp dir " << system_tempdir << endl;
202 if (destroyDir(system_tempdir) != 0) {
204 boost::format fmt = _("Could not remove the temporary directory %1$s");
205 fmt % system_tempdir;
206 string msg = fmt.str();
208 string msg = _("Could not remove the temporary directory ") + system_tempdir;
210 Alert::warning(_("Could not remove temporary directory"), msg);
219 class AutoSaveBuffer : public ForkedProcess {
222 AutoSaveBuffer(BufferView & bv, string const & fname)
223 : bv_(bv), fname_(fname) {}
225 virtual ForkedProcess * clone() const {
226 return new AutoSaveBuffer(*this);
232 virtual int generateChild();
239 int AutoSaveBuffer::start()
242 command_ = boost::io::str(boost::format(_("Auto-saving %1$s")) % fname_);
244 command_ = _("Auto-saving ") + fname_;
246 return runNonBlocking();
250 int AutoSaveBuffer::generateChild()
252 // tmp_ret will be located (usually) in /tmp
253 // will that be a problem?
254 pid_t const pid = fork(); // If you want to debug the autosave
255 // you should set pid to -1, and comment out the
257 if (pid == 0 || pid == -1) {
258 // pid = -1 signifies that lyx was unable
259 // to fork. But we will do the save
263 string const tmp_ret = lyx::tempName(string(), "lyxauto");
264 if (!tmp_ret.empty()) {
265 bv_.buffer()->writeFile(tmp_ret);
266 // assume successful write of tmp_ret
267 if (!lyx::rename(tmp_ret, fname_)) {
269 // most likely couldn't move between filesystems
270 // unless write of tmp_ret failed
271 // so remove tmp file (if it exists)
272 lyx::unlink(tmp_ret);
279 // failed to write/rename tmp_ret so try writing direct
280 if (!bv_.buffer()->writeFile(fname_)) {
281 // It is dangerous to do this in the child,
282 // but safe in the parent, so...
284 bv_.owner()->message(_("Autosave failed!"));
287 if (pid == 0) { // we are the child so...
297 void AutoSave(BufferView * bv)
298 // should probably be moved into BufferList (Lgb)
299 // Perfect target for a thread...
301 if (!bv->available())
304 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
305 // We don't save now, but we'll try again later
306 bv->owner()->resetAutosaveTimer();
310 bv->owner()->message(_("Autosaving current document..."));
312 // create autosave filename
313 string fname = bv->buffer()->filePath();
315 fname += OnlyFilename(bv->buffer()->fileName());
318 AutoSaveBuffer autosave(*bv, fname);
321 bv->buffer()->markBakClean();
322 bv->owner()->resetAutosaveTimer();
327 // Copyright CHT Software Service GmbH
330 // create new file with template
333 Buffer * NewFile(string const & filename)
335 // Split argument by :
337 string tmpname = split(filename, name, ':');
338 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
339 if (name.length() == 1
340 && isalpha(static_cast<unsigned char>(name[0]))
341 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
343 name += token(tmpname, ':', 0);
344 tmpname = split(tmpname, ':');
347 lyxerr[Debug::INFO] << "Arg is " << filename
348 << "\nName is " << name
349 << "\nTemplate is " << tmpname << endl;
351 // find a free buffer
352 Buffer * tmpbuf = bufferlist.newFile(name, tmpname);
354 lastfiles->newFile(tmpbuf->fileName());
359 // Insert ascii file (if filename is empty, prompt for one)
360 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
362 if (!bv->available())
365 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
372 // clear the selection
373 bool flag = (bv->text == bv->getLyXText());
375 bv->beforeChange(bv->text);
377 bv->getLyXText()->insertStringAsLines(tmpstr);
379 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
381 bv->update(BufferView::SELECT);
385 // Insert ascii file (if filename is empty, prompt for one)
386 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
391 FileDialog fileDlg(_("Select file to insert"),
392 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
394 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
396 if (result.first == FileDialog::Later)
399 fname = result.second;
407 if (!fi.readable()) {
408 string const error = strerror(errno);
409 string const file = MakeDisplayPath(fname, 50);
411 boost::format fmt(_("Could not read the specified document\n%1$s\ndue to the error: %2$s"));
414 string text = fmt.str();
416 string text = _("Could not read the specified document\n");
417 text += file + _(" due to the error: ");
420 Alert::error(_("Could not read file"), text);
424 ifstream ifs(fname.c_str());
426 string const error = strerror(errno);
427 string const file = MakeDisplayPath(fname, 50);
429 boost::format fmt(_("Could not open the specified document\n%1$s\ndue to the error: %2$s"));
432 string text = fmt.str();
434 string text = _("Could not open the specified document\n");
435 text += file + _(" due to the error: ");
438 Alert::error(_("Could not open file"), text);
442 ifs.unsetf(ios::skipws);
443 istream_iterator<char> ii(ifs);
444 istream_iterator<char> end;
445 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
446 // We use this until the compilers get better...
448 copy(ii, end, back_inserter(tmp));
449 string const tmpstr(tmp.begin(), tmp.end());
451 // This is what we want to use and what we will use once the
452 // compilers get good enough.
453 //string tmpstr(ii, end); // yet a reason for using std::string
454 // alternate approach to get the file into a string:
456 copy(ii, end, back_inserter(tmpstr));
463 string const getPossibleLabel(BufferView const & bv)
465 Paragraph * par = &*bv.getLyXText()->cursor.par();
466 LyXLayout_ptr layout = par->layout();
467 if (layout->latextype == LATEX_PARAGRAPH && par->previous()) {
468 Paragraph * par2 = par->previous();
470 LyXLayout_ptr const & layout2 = par2->layout();
472 if (layout2->latextype != LATEX_PARAGRAPH) {
478 string text = layout->latexname().substr(0, 3);
479 if (layout->latexname() == "theorem")
480 text = "thm"; // Create a correct prefix for prettyref
483 if (layout->latextype == LATEX_PARAGRAPH ||
484 lyxrc.label_init_length < 0)
487 string par_text = par->asString(bv.buffer(), false);
488 for (int i = 0; i < lyxrc.label_init_length; ++i) {
489 if (par_text.empty())
492 par_text = split(par_text, head, ' ');
494 text += '-'; // Is it legal to use spaces in
503 // This function runs "configure" and then rereads lyx.defaults to
504 // reconfigure the automatic settings.
505 void Reconfigure(BufferView * bv)
507 bv->owner()->message(_("Running configure..."));
509 // Run configure in user lyx directory
512 one.startscript(Systemcall::Wait,
513 AddName(system_lyxdir, "configure"));
515 bv->owner()->message(_("Reloading configuration..."));
516 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
518 Alert::information(_("System reconfigured"),
519 _("The system has been reconfigured.\n"
520 "You need to restart LyX to make use of any \n"
521 "updated document class specifications."));