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
67 bool MenuWrite(Buffer * buffer)
70 lastfiles->newFile(buffer->fileName());
74 // FIXME: we don't tell the user *WHY* the save failed !!
76 string const file = MakeDisplayPath(buffer->fileName(), 30);
78 string text = bformat(_("The document %1$s could not be saved.\n\n"
79 "Do you want to rename the document and try again?"), file);
80 int const ret = Alert::prompt(_("Rename and save?"),
81 text, 0, 1, _("&Rename"), _("&Cancel"));
84 return WriteAs(buffer);
90 bool WriteAs(Buffer * buffer, string const & filename)
92 string fname = buffer->fileName();
93 string const oldname = fname;
95 if (filename.empty()) {
97 FileDialog fileDlg(_("Choose a filename to save document as"),
99 make_pair(string(_("Documents|#o#O")),
100 string(lyxrc.document_path)),
101 make_pair(string(_("Templates|#T#t")),
102 string(lyxrc.template_path)));
104 if (!IsLyXFilename(fname))
107 FileDialog::Result result =
108 fileDlg.save(OnlyPath(fname),
109 _("*.lyx| LyX Documents (*.lyx)"),
110 OnlyFilename(fname));
112 if (result.first == FileDialog::Later)
115 fname = result.second;
120 // Make sure the absolute filename ends with appropriate suffix
121 fname = MakeAbsPath(fname);
122 if (!IsLyXFilename(fname))
127 FileInfo const myfile(fname);
129 string const file = MakeDisplayPath(fname, 30);
130 string text = bformat(_("The document %1$s already exists.\n\n"
131 "Do you want to over-write that document?"), file);
132 int const ret = Alert::prompt(_("Over-write document?"),
133 text, 0, 1, _("&Over-write"), _("&Cancel"));
139 // Ok, change the name of the buffer
140 buffer->setFileName(fname);
142 bool unnamed = buffer->isUnnamed();
143 buffer->setUnnamed(false);
145 if (!MenuWrite(buffer)) {
146 buffer->setFileName(oldname);
147 buffer->setUnnamed(unnamed);
151 removeAutosaveFile(oldname);
158 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
160 if (lyx_gui::use_gui) {
161 if (!bufferlist.quitWriteAll())
164 lastfiles->writeFile(lyxrc.lastfiles);
167 // Set a flag that we do quitting from the program,
168 // so no refreshes are necessary.
171 // close buffers first
172 bufferlist.closeAll();
174 // do any other cleanup procedures now
175 lyxerr[Debug::INFO] << "Deleting tmp dir " << system_tempdir << endl;
177 if (destroyDir(system_tempdir) != 0) {
178 string msg = bformat(_("Could not remove the temporary directory %1$s"),
180 Alert::warning(_("Could not remove temporary directory"), msg);
189 class AutoSaveBuffer : public ForkedProcess {
192 AutoSaveBuffer(BufferView & bv, string const & fname)
193 : bv_(bv), fname_(fname) {}
195 virtual ForkedProcess * clone() const {
196 return new AutoSaveBuffer(*this);
202 virtual int generateChild();
209 int AutoSaveBuffer::start()
211 command_ = bformat(_("Auto-saving %1$s"), fname_);
212 return runNonBlocking();
216 int AutoSaveBuffer::generateChild()
218 // tmp_ret will be located (usually) in /tmp
219 // will that be a problem?
220 pid_t const pid = fork(); // If you want to debug the autosave
221 // you should set pid to -1, and comment out the
223 if (pid == 0 || pid == -1) {
224 // pid = -1 signifies that lyx was unable
225 // to fork. But we will do the save
229 string const tmp_ret = tempName(string(), "lyxauto");
230 if (!tmp_ret.empty()) {
231 bv_.buffer()->writeFile(tmp_ret);
232 // assume successful write of tmp_ret
233 if (!rename(tmp_ret, fname_)) {
235 // most likely couldn't move between filesystems
236 // unless write of tmp_ret failed
237 // so remove tmp file (if it exists)
245 // failed to write/rename tmp_ret so try writing direct
246 if (!bv_.buffer()->writeFile(fname_)) {
247 // It is dangerous to do this in the child,
248 // but safe in the parent, so...
250 bv_.owner()->message(_("Autosave failed!"));
253 if (pid == 0) { // we are the child so...
263 void AutoSave(BufferView * bv)
264 // should probably be moved into BufferList (Lgb)
265 // Perfect target for a thread...
267 if (!bv->available())
270 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
271 // We don't save now, but we'll try again later
272 bv->owner()->resetAutosaveTimer();
276 bv->owner()->message(_("Autosaving current document..."));
278 // create autosave filename
279 string fname = bv->buffer()->filePath();
281 fname += OnlyFilename(bv->buffer()->fileName());
284 AutoSaveBuffer autosave(*bv, fname);
287 bv->buffer()->markBakClean();
288 bv->owner()->resetAutosaveTimer();
293 // Copyright CHT Software Service GmbH
296 // create new file with template
299 void NewFile(BufferView * bv, string const & filename)
301 // Split argument by :
303 string tmpname = split(filename, name, ':');
304 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
305 if (name.length() == 1
306 && isalpha(static_cast<unsigned char>(name[0]))
307 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
309 name += token(tmpname, ':', 0);
310 tmpname = split(tmpname, ':');
313 lyxerr[Debug::INFO] << "Arg is " << filename
314 << "\nName is " << name
315 << "\nTemplate is " << tmpname << endl;
317 bv->newFile(name, tmpname);
321 // Insert ascii file (if filename is empty, prompt for one)
322 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
324 if (!bv->available())
327 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
331 // clear the selection
332 bool flag = (bv->text == bv->getLyXText());
334 bv->beforeChange(bv->text);
336 bv->getLyXText()->insertStringAsLines(tmpstr);
338 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
340 bv->update(BufferView::SELECT);
344 // Insert ascii file (if filename is empty, prompt for one)
345 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
350 FileDialog fileDlg(_("Select file to insert"),
351 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
353 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
355 if (result.first == FileDialog::Later)
358 fname = result.second;
366 if (!fi.readable()) {
367 string const error = strerror(errno);
368 string const file = MakeDisplayPath(fname, 50);
369 string const text = bformat(_("Could not read the specified document\n"
370 "%1$s\ndue to the error: %2$s"), file, error);
371 Alert::error(_("Could not read file"), text);
375 ifstream ifs(fname.c_str());
377 string const error = strerror(errno);
378 string const file = MakeDisplayPath(fname, 50);
379 string const text = bformat(_("Could not open the specified document\n"
380 "%1$s\ndue to the error: %2$s"), file, error);
381 Alert::error(_("Could not open file"), text);
385 ifs.unsetf(ios::skipws);
386 istream_iterator<char> ii(ifs);
387 istream_iterator<char> end;
388 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
389 // We use this until the compilers get better...
391 copy(ii, end, back_inserter(tmp));
392 string const tmpstr(tmp.begin(), tmp.end());
394 // This is what we want to use and what we will use once the
395 // compilers get good enough.
396 //string tmpstr(ii, end); // yet a reason for using std::string
397 // alternate approach to get the file into a string:
399 copy(ii, end, back_inserter(tmpstr));
406 string const getPossibleLabel(BufferView const & bv)
408 ParagraphList::iterator pit = bv.getLyXText()->cursor.par();
409 ParagraphList & plist = bv.getLyXText()->ownerParagraphs();
411 LyXLayout_ptr layout = pit->layout();
413 if (layout->latextype == LATEX_PARAGRAPH && pit != plist.begin()) {
414 ParagraphList::iterator pit2 = boost::prior(pit);
416 LyXLayout_ptr const & layout2 = pit2->layout();
418 if (layout2->latextype != LATEX_PARAGRAPH) {
424 string text = layout->latexname().substr(0, 3);
425 if (layout->latexname() == "theorem")
426 text = "thm"; // Create a correct prefix for prettyref
429 if (layout->latextype == LATEX_PARAGRAPH ||
430 lyxrc.label_init_length < 0)
433 string par_text = pit->asString(bv.buffer(), false);
434 for (int i = 0; i < lyxrc.label_init_length; ++i) {
435 if (par_text.empty())
438 par_text = split(par_text, head, ' ');
440 text += '-'; // Is it legal to use spaces in
449 // This function runs "configure" and then rereads lyx.defaults to
450 // reconfigure the automatic settings.
451 void Reconfigure(BufferView * bv)
453 bv->owner()->message(_("Running configure..."));
455 // Run configure in user lyx directory
458 one.startscript(Systemcall::Wait,
459 AddName(system_lyxdir, "configure"));
461 bv->owner()->message(_("Reloading configuration..."));
462 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
464 Alert::information(_("System reconfigured"),
465 _("The system has been reconfigured.\n"
466 "You need to restart LyX to make use of any \n"
467 "updated document class specifications."));