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 "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferview_funcs.h"
20 #include "lastfiles.h"
24 #include "BufferView.h"
27 #include "insets/insetlabel.h"
29 #include "frontends/lyx_gui.h"
30 #include "frontends/LyXView.h"
31 #include "frontends/Alert.h"
32 #include "frontends/FileDialog.h"
34 #include "support/FileInfo.h"
35 #include "support/filetools.h"
36 #include "support/forkedcall.h"
37 #include "support/path.h"
38 #include "support/systemcall.h"
39 #include "support/lstrings.h"
46 using namespace lyx::support;
53 using std::back_inserter;
54 using std::istream_iterator;
58 extern BufferList bufferlist;
59 // this should be static, but I need it in buffer.C
60 bool quitting; // flag, that we are quitting the program
63 void ShowMessage(Buffer const * buf,
69 && buf && buf->getUser() && buf->getUser()->owner()) {
70 string const str = msg1 + ' ' + msg2 + ' ' + msg3;
71 buf->getUser()->owner()->message(str);
73 lyxerr << msg1 << msg2 << msg3 << endl;
81 bool MenuWrite(Buffer * buffer)
84 lastfiles->newFile(buffer->fileName());
88 // FIXME: we don't tell the user *WHY* the save failed !!
90 string const file = MakeDisplayPath(buffer->fileName(), 30);
92 string text = bformat(_("The document %1$s could not be saved.\n\n"
93 "Do you want to rename the document and try again?"), file);
94 int const ret = Alert::prompt(_("Rename and save?"),
95 text, 0, 1, _("&Rename"), _("&Cancel"));
98 return WriteAs(buffer);
104 bool WriteAs(Buffer * buffer, string const & filename)
106 string fname = buffer->fileName();
107 string const oldname = fname;
109 if (filename.empty()) {
111 FileDialog fileDlg(_("Choose a filename to save document as"),
113 make_pair(string(_("Documents|#o#O")),
114 string(lyxrc.document_path)),
115 make_pair(string(_("Templates|#T#t")),
116 string(lyxrc.template_path)));
118 if (!IsLyXFilename(fname))
121 FileDialog::Result result =
122 fileDlg.save(OnlyPath(fname),
123 _("*.lyx| LyX Documents (*.lyx)"),
124 OnlyFilename(fname));
126 if (result.first == FileDialog::Later)
129 fname = result.second;
134 // Make sure the absolute filename ends with appropriate suffix
135 fname = MakeAbsPath(fname);
136 if (!IsLyXFilename(fname))
141 FileInfo const myfile(fname);
143 string const file = MakeDisplayPath(fname, 30);
144 string text = bformat(_("The document %1$s already exists.\n\n"
145 "Do you want to over-write that document?"), file);
146 int const ret = Alert::prompt(_("Over-write document?"),
147 text, 0, 1, _("&Over-write"), _("&Cancel"));
153 // Ok, change the name of the buffer
154 buffer->setFileName(fname);
156 bool unnamed = buffer->isUnnamed();
157 buffer->setUnnamed(false);
159 if (!MenuWrite(buffer)) {
160 buffer->setFileName(oldname);
161 buffer->setUnnamed(unnamed);
165 removeAutosaveFile(oldname);
172 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
174 if (lyx_gui::use_gui) {
175 if (!bufferlist.quitWriteAll())
178 lastfiles->writeFile(lyxrc.lastfiles);
181 // Set a flag that we do quitting from the program,
182 // so no refreshes are necessary.
185 // close buffers first
186 bufferlist.closeAll();
188 // do any other cleanup procedures now
189 lyxerr[Debug::INFO] << "Deleting tmp dir " << system_tempdir << endl;
191 if (destroyDir(system_tempdir) != 0) {
192 string msg = bformat(_("Could not remove the temporary directory %1$s"),
194 Alert::warning(_("Could not remove temporary directory"), msg);
203 class AutoSaveBuffer : public ForkedProcess {
206 AutoSaveBuffer(BufferView & bv, string const & fname)
207 : bv_(bv), fname_(fname) {}
209 virtual ForkedProcess * clone() const {
210 return new AutoSaveBuffer(*this);
216 virtual int generateChild();
223 int AutoSaveBuffer::start()
225 command_ = bformat(_("Auto-saving %1$s"), fname_);
226 return runNonBlocking();
230 int AutoSaveBuffer::generateChild()
232 // tmp_ret will be located (usually) in /tmp
233 // will that be a problem?
234 pid_t const pid = fork(); // If you want to debug the autosave
235 // you should set pid to -1, and comment out the
237 if (pid == 0 || pid == -1) {
238 // pid = -1 signifies that lyx was unable
239 // to fork. But we will do the save
243 string const tmp_ret = tempName(string(), "lyxauto");
244 if (!tmp_ret.empty()) {
245 bv_.buffer()->writeFile(tmp_ret);
246 // assume successful write of tmp_ret
247 if (!rename(tmp_ret, fname_)) {
249 // most likely couldn't move between filesystems
250 // unless write of tmp_ret failed
251 // so remove tmp file (if it exists)
259 // failed to write/rename tmp_ret so try writing direct
260 if (!bv_.buffer()->writeFile(fname_)) {
261 // It is dangerous to do this in the child,
262 // but safe in the parent, so...
264 bv_.owner()->message(_("Autosave failed!"));
267 if (pid == 0) { // we are the child so...
277 void AutoSave(BufferView * bv)
278 // should probably be moved into BufferList (Lgb)
279 // Perfect target for a thread...
281 if (!bv->available())
284 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
285 // We don't save now, but we'll try again later
286 bv->owner()->resetAutosaveTimer();
290 bv->owner()->message(_("Autosaving current document..."));
292 // create autosave filename
293 string fname = bv->buffer()->filePath();
295 fname += OnlyFilename(bv->buffer()->fileName());
298 AutoSaveBuffer autosave(*bv, fname);
301 bv->buffer()->markBakClean();
302 bv->owner()->resetAutosaveTimer();
307 // Copyright CHT Software Service GmbH
310 // create new file with template
313 Buffer * NewFile(string const & filename)
315 // Split argument by :
317 string tmpname = split(filename, name, ':');
318 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
319 if (name.length() == 1
320 && isalpha(static_cast<unsigned char>(name[0]))
321 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
323 name += token(tmpname, ':', 0);
324 tmpname = split(tmpname, ':');
327 lyxerr[Debug::INFO] << "Arg is " << filename
328 << "\nName is " << name
329 << "\nTemplate is " << tmpname << endl;
331 // find a free buffer
332 Buffer * tmpbuf = newFile(name, tmpname);
334 lastfiles->newFile(tmpbuf->fileName());
339 // Insert ascii file (if filename is empty, prompt for one)
340 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
342 if (!bv->available())
345 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
349 // clear the selection
350 bool flag = (bv->text == bv->getLyXText());
352 bv->beforeChange(bv->text);
354 bv->getLyXText()->insertStringAsLines(tmpstr);
356 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
358 bv->update(BufferView::SELECT);
362 // Insert ascii file (if filename is empty, prompt for one)
363 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
368 FileDialog fileDlg(_("Select file to insert"),
369 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
371 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
373 if (result.first == FileDialog::Later)
376 fname = result.second;
384 if (!fi.readable()) {
385 string const error = strerror(errno);
386 string const file = MakeDisplayPath(fname, 50);
387 string const text = bformat(_("Could not read the specified document\n"
388 "%1$s\ndue to the error: %2$s"), file, error);
389 Alert::error(_("Could not read file"), text);
393 ifstream ifs(fname.c_str());
395 string const error = strerror(errno);
396 string const file = MakeDisplayPath(fname, 50);
397 string const text = bformat(_("Could not open the specified document\n"
398 "%1$s\ndue to the error: %2$s"), file, error);
399 Alert::error(_("Could not open file"), text);
403 ifs.unsetf(ios::skipws);
404 istream_iterator<char> ii(ifs);
405 istream_iterator<char> end;
406 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
407 // We use this until the compilers get better...
409 copy(ii, end, back_inserter(tmp));
410 string const tmpstr(tmp.begin(), tmp.end());
412 // This is what we want to use and what we will use once the
413 // compilers get good enough.
414 //string tmpstr(ii, end); // yet a reason for using std::string
415 // alternate approach to get the file into a string:
417 copy(ii, end, back_inserter(tmpstr));
424 string const getPossibleLabel(BufferView const & bv)
426 ParagraphList::iterator pit = bv.getLyXText()->cursor.par();
427 ParagraphList & plist = bv.getLyXText()->ownerParagraphs();
429 LyXLayout_ptr layout = pit->layout();
431 if (layout->latextype == LATEX_PARAGRAPH && pit != plist.begin()) {
432 ParagraphList::iterator pit2 = boost::prior(pit);
434 LyXLayout_ptr const & layout2 = pit2->layout();
436 if (layout2->latextype != LATEX_PARAGRAPH) {
442 string text = layout->latexname().substr(0, 3);
443 if (layout->latexname() == "theorem")
444 text = "thm"; // Create a correct prefix for prettyref
447 if (layout->latextype == LATEX_PARAGRAPH ||
448 lyxrc.label_init_length < 0)
451 string par_text = pit->asString(bv.buffer(), false);
452 for (int i = 0; i < lyxrc.label_init_length; ++i) {
453 if (par_text.empty())
456 par_text = split(par_text, head, ' ');
458 text += '-'; // Is it legal to use spaces in
467 // This function runs "configure" and then rereads lyx.defaults to
468 // reconfigure the automatic settings.
469 void Reconfigure(BufferView * bv)
471 bv->owner()->message(_("Running configure..."));
473 // Run configure in user lyx directory
476 one.startscript(Systemcall::Wait,
477 AddName(system_lyxdir, "configure"));
479 bv->owner()->message(_("Reloading configuration..."));
480 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
482 Alert::information(_("System reconfigured"),
483 _("The system has been reconfigured.\n"
484 "You need to restart LyX to make use of any \n"
485 "updated document class specifications."));