3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Angus Leeming
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferview_funcs.h"
24 #include "lastfiles.h"
28 #include "BufferView.h"
31 #include "insets/insetlabel.h"
33 #include "frontends/lyx_gui.h"
34 #include "frontends/LyXView.h"
35 #include "frontends/Alert.h"
36 #include "frontends/FileDialog.h"
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"
52 using namespace lyx::support;
59 using std::back_inserter;
60 using std::istream_iterator;
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
73 bool MenuWrite(Buffer * buffer)
76 lastfiles->newFile(buffer->fileName());
80 // FIXME: we don't tell the user *WHY* the save failed !!
82 string const file = MakeDisplayPath(buffer->fileName(), 30);
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"));
90 return WriteAs(buffer);
96 bool WriteAs(Buffer * buffer, string const & filename)
98 string fname = buffer->fileName();
99 string const oldname = fname;
101 if (filename.empty()) {
103 FileDialog fileDlg(_("Choose a filename to save document as"),
105 make_pair(string(_("Documents|#o#O")),
106 string(lyxrc.document_path)),
107 make_pair(string(_("Templates|#T#t")),
108 string(lyxrc.template_path)));
110 if (!IsLyXFilename(fname))
113 FileDialog::Result result =
114 fileDlg.save(OnlyPath(fname),
115 _("*.lyx| LyX Documents (*.lyx)"),
116 OnlyFilename(fname));
118 if (result.first == FileDialog::Later)
121 fname = result.second;
126 // Make sure the absolute filename ends with appropriate suffix
127 fname = MakeAbsPath(fname);
128 if (!IsLyXFilename(fname))
133 FileInfo const myfile(fname);
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"));
145 // Ok, change the name of the buffer
146 buffer->setFileName(fname);
148 bool unnamed = buffer->isUnnamed();
149 buffer->setUnnamed(false);
151 if (!MenuWrite(buffer)) {
152 buffer->setFileName(oldname);
153 buffer->setUnnamed(unnamed);
157 removeAutosaveFile(oldname);
164 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
166 if (lyx_gui::use_gui) {
167 if (!bufferlist.quitWriteAll())
170 lastfiles->writeFile(lyxrc.lastfiles);
173 // Set a flag that we do quitting from the program,
174 // so no refreshes are necessary.
177 // close buffers first
178 bufferlist.closeAll();
180 // do any other cleanup procedures now
181 lyxerr[Debug::INFO] << "Deleting tmp dir " << os::getTmpDir() << endl;
183 if (destroyDir(os::getTmpDir()) != 0) {
184 string msg = bformat(_("Could not remove the temporary directory %1$s"),
186 Alert::warning(_("Could not remove temporary directory"), msg);
195 class AutoSaveBuffer : public ForkedProcess {
198 AutoSaveBuffer(BufferView & bv, string const & fname)
199 : bv_(bv), fname_(fname) {}
201 virtual ForkedProcess * clone() const {
202 return new AutoSaveBuffer(*this);
208 virtual int generateChild();
215 int AutoSaveBuffer::start()
217 command_ = bformat(_("Auto-saving %1$s"), fname_);
218 return runNonBlocking();
222 int AutoSaveBuffer::generateChild()
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
229 if (pid == 0 || pid == -1) {
230 // pid = -1 signifies that lyx was unable
231 // to fork. But we will do the save
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_)) {
241 // most likely couldn't move between filesystems
242 // unless write of tmp_ret failed
243 // so remove tmp file (if it exists)
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...
256 bv_.owner()->message(_("Autosave failed!"));
259 if (pid == 0) { // we are the child so...
269 void AutoSave(BufferView * bv)
270 // should probably be moved into BufferList (Lgb)
271 // Perfect target for a thread...
273 if (!bv->available())
276 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
277 // We don't save now, but we'll try again later
278 bv->owner()->resetAutosaveTimer();
282 bv->owner()->message(_("Autosaving current document..."));
284 // create autosave filename
285 string fname = bv->buffer()->filePath();
287 fname += OnlyFilename(bv->buffer()->fileName());
290 AutoSaveBuffer autosave(*bv, fname);
293 bv->buffer()->markBakClean();
294 bv->owner()->resetAutosaveTimer();
299 // Copyright CHT Software Service GmbH
302 // create new file with template
305 void NewFile(BufferView * bv, string const & filename)
307 // Split argument by :
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, "\\"))) {
315 name += token(tmpname, ':', 0);
316 tmpname = split(tmpname, ':');
319 lyxerr[Debug::INFO] << "Arg is " << filename
320 << "\nName is " << name
321 << "\nTemplate is " << tmpname << endl;
323 bv->newFile(name, tmpname);
327 // Insert ascii file (if filename is empty, prompt for one)
328 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
330 if (!bv->available())
333 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
337 // clear the selection
338 bool flag = (bv->text == bv->getLyXText());
340 bv->beforeChange(bv->text);
342 bv->getLyXText()->insertStringAsLines(tmpstr);
344 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
349 // Insert ascii file (if filename is empty, prompt for one)
350 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
355 FileDialog fileDlg(_("Select file to insert"),
356 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
358 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
360 if (result.first == FileDialog::Later)
363 fname = result.second;
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);
380 ifstream ifs(fname.c_str());
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);
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...
396 copy(ii, end, back_inserter(tmp));
397 string const tmpstr(tmp.begin(), tmp.end());
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:
404 copy(ii, end, back_inserter(tmpstr));
411 string const getPossibleLabel(BufferView const & bv)
413 ParagraphList::iterator pit = bv.getLyXText()->cursor.par();
414 ParagraphList & plist = bv.getLyXText()->ownerParagraphs();
416 LyXLayout_ptr layout = pit->layout();
418 if (layout->latextype == LATEX_PARAGRAPH && pit != plist.begin()) {
419 ParagraphList::iterator pit2 = boost::prior(pit);
421 LyXLayout_ptr const & layout2 = pit2->layout();
423 if (layout2->latextype != LATEX_PARAGRAPH) {
429 string text = layout->latexname().substr(0, 3);
430 if (layout->latexname() == "theorem")
431 text = "thm"; // Create a correct prefix for prettyref
434 if (layout->latextype == LATEX_PARAGRAPH ||
435 lyxrc.label_init_length < 0)
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())
443 par_text = split(par_text, head, ' ');
445 text += '-'; // Is it legal to use spaces in
454 // This function runs "configure" and then rereads lyx.defaults to
455 // reconfigure the automatic settings.
456 void Reconfigure(BufferView * bv)
458 bv->owner()->message(_("Running configure..."));
460 // Run configure in user lyx directory
461 Path p(user_lyxdir());
463 one.startscript(Systemcall::Wait,
464 AddName(system_lyxdir(), "configure"));
466 bv->owner()->message(_("Reloading configuration..."));
467 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
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."));