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/os.h"
46 #include "support/systemcall.h"
53 using namespace lyx::support;
60 using std::back_inserter;
61 using std::istream_iterator;
65 extern BufferList bufferlist;
66 // this should be static, but I need it in buffer.C
67 bool quitting; // flag, that we are quitting the program
74 bool MenuWrite(Buffer * buffer)
77 lastfiles->newFile(buffer->fileName());
81 // FIXME: we don't tell the user *WHY* the save failed !!
83 string const file = MakeDisplayPath(buffer->fileName(), 30);
85 string text = bformat(_("The document %1$s could not be saved.\n\n"
86 "Do you want to rename the document and try again?"), file);
87 int const ret = Alert::prompt(_("Rename and save?"),
88 text, 0, 1, _("&Rename"), _("&Cancel"));
91 return WriteAs(buffer);
97 bool WriteAs(Buffer * buffer, string const & filename)
99 string fname = buffer->fileName();
100 string const oldname = fname;
102 if (filename.empty()) {
104 FileDialog fileDlg(_("Choose a filename to save document as"),
106 make_pair(string(_("Documents|#o#O")),
107 string(lyxrc.document_path)),
108 make_pair(string(_("Templates|#T#t")),
109 string(lyxrc.template_path)));
111 if (!IsLyXFilename(fname))
114 FileDialog::Result result =
115 fileDlg.save(OnlyPath(fname),
116 _("*.lyx| LyX Documents (*.lyx)"),
117 OnlyFilename(fname));
119 if (result.first == FileDialog::Later)
122 fname = result.second;
127 // Make sure the absolute filename ends with appropriate suffix
128 fname = MakeAbsPath(fname);
129 if (!IsLyXFilename(fname))
134 FileInfo const myfile(fname);
136 string const file = MakeDisplayPath(fname, 30);
137 string text = bformat(_("The document %1$s already exists.\n\n"
138 "Do you want to over-write that document?"), file);
139 int const ret = Alert::prompt(_("Over-write document?"),
140 text, 0, 1, _("&Over-write"), _("&Cancel"));
146 // Ok, change the name of the buffer
147 buffer->setFileName(fname);
149 bool unnamed = buffer->isUnnamed();
150 buffer->setUnnamed(false);
152 if (!MenuWrite(buffer)) {
153 buffer->setFileName(oldname);
154 buffer->setUnnamed(unnamed);
158 removeAutosaveFile(oldname);
165 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
167 if (lyx_gui::use_gui) {
168 if (!bufferlist.quitWriteAll())
171 lastfiles->writeFile(lyxrc.lastfiles);
174 // Set a flag that we do quitting from the program,
175 // so no refreshes are necessary.
178 // close buffers first
179 bufferlist.closeAll();
181 // do any other cleanup procedures now
182 lyxerr[Debug::INFO] << "Deleting tmp dir " << os::getTmpDir() << endl;
184 if (destroyDir(os::getTmpDir()) != 0) {
185 string msg = bformat(_("Could not remove the temporary directory %1$s"),
187 Alert::warning(_("Could not remove temporary directory"), msg);
196 class AutoSaveBuffer : public ForkedProcess {
199 AutoSaveBuffer(BufferView & bv, string const & fname)
200 : bv_(bv), fname_(fname) {}
202 virtual ForkedProcess * clone() const {
203 return new AutoSaveBuffer(*this);
209 virtual int generateChild();
216 int AutoSaveBuffer::start()
218 command_ = bformat(_("Auto-saving %1$s"), fname_);
219 return runNonBlocking();
223 int AutoSaveBuffer::generateChild()
225 // tmp_ret will be located (usually) in /tmp
226 // will that be a problem?
227 pid_t const pid = fork(); // If you want to debug the autosave
228 // you should set pid to -1, and comment out the
230 if (pid == 0 || pid == -1) {
231 // pid = -1 signifies that lyx was unable
232 // to fork. But we will do the save
236 string const tmp_ret = tempName(string(), "lyxauto");
237 if (!tmp_ret.empty()) {
238 bv_.buffer()->writeFile(tmp_ret);
239 // assume successful write of tmp_ret
240 if (!rename(tmp_ret, fname_)) {
242 // most likely couldn't move between filesystems
243 // unless write of tmp_ret failed
244 // so remove tmp file (if it exists)
252 // failed to write/rename tmp_ret so try writing direct
253 if (!bv_.buffer()->writeFile(fname_)) {
254 // It is dangerous to do this in the child,
255 // but safe in the parent, so...
257 bv_.owner()->message(_("Autosave failed!"));
260 if (pid == 0) { // we are the child so...
270 void AutoSave(BufferView * bv)
271 // should probably be moved into BufferList (Lgb)
272 // Perfect target for a thread...
274 if (!bv->available())
277 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
278 // We don't save now, but we'll try again later
279 bv->owner()->resetAutosaveTimer();
283 bv->owner()->message(_("Autosaving current document..."));
285 // create autosave filename
286 string fname = bv->buffer()->filePath();
288 fname += OnlyFilename(bv->buffer()->fileName());
291 AutoSaveBuffer autosave(*bv, fname);
294 bv->buffer()->markBakClean();
295 bv->owner()->resetAutosaveTimer();
300 // Copyright CHT Software Service GmbH
303 // create new file with template
306 void NewFile(BufferView * bv, string const & filename)
308 // Split argument by :
310 string tmpname = split(filename, name, ':');
311 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
312 if (name.length() == 1
313 && isalpha(static_cast<unsigned char>(name[0]))
314 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
316 name += token(tmpname, ':', 0);
317 tmpname = split(tmpname, ':');
320 lyxerr[Debug::INFO] << "Arg is " << filename
321 << "\nName is " << name
322 << "\nTemplate is " << tmpname << endl;
324 bv->newFile(name, tmpname);
328 // Insert ascii file (if filename is empty, prompt for one)
329 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
331 if (!bv->available())
334 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
338 // clear the selection
339 bool flag = (bv->text == bv->getLyXText());
341 bv->beforeChange(bv->text);
343 bv->getLyXText()->insertStringAsLines(tmpstr);
345 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
350 // Insert ascii file (if filename is empty, prompt for one)
351 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
356 FileDialog fileDlg(_("Select file to insert"),
357 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
359 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
361 if (result.first == FileDialog::Later)
364 fname = result.second;
372 if (!fi.readable()) {
373 string const error = strerror(errno);
374 string const file = MakeDisplayPath(fname, 50);
375 string const text = bformat(_("Could not read the specified document\n"
376 "%1$s\ndue to the error: %2$s"), file, error);
377 Alert::error(_("Could not read file"), text);
381 ifstream ifs(fname.c_str());
383 string const error = strerror(errno);
384 string const file = MakeDisplayPath(fname, 50);
385 string const text = bformat(_("Could not open the specified document\n"
386 "%1$s\ndue to the error: %2$s"), file, error);
387 Alert::error(_("Could not open file"), text);
391 ifs.unsetf(ios::skipws);
392 istream_iterator<char> ii(ifs);
393 istream_iterator<char> end;
394 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
395 // We use this until the compilers get better...
397 copy(ii, end, back_inserter(tmp));
398 string const tmpstr(tmp.begin(), tmp.end());
400 // This is what we want to use and what we will use once the
401 // compilers get good enough.
402 //string tmpstr(ii, end); // yet a reason for using std::string
403 // alternate approach to get the file into a string:
405 copy(ii, end, back_inserter(tmpstr));
412 string const getPossibleLabel(BufferView const & bv)
414 ParagraphList::iterator pit = bv.getLyXText()->cursor.par();
415 ParagraphList & plist = bv.getLyXText()->ownerParagraphs();
417 LyXLayout_ptr layout = pit->layout();
419 if (layout->latextype == LATEX_PARAGRAPH && pit != plist.begin()) {
420 ParagraphList::iterator pit2 = boost::prior(pit);
422 LyXLayout_ptr const & layout2 = pit2->layout();
424 if (layout2->latextype != LATEX_PARAGRAPH) {
430 string text = layout->latexname().substr(0, 3);
431 if (layout->latexname() == "theorem")
432 text = "thm"; // Create a correct prefix for prettyref
435 if (layout->latextype == LATEX_PARAGRAPH ||
436 lyxrc.label_init_length < 0)
439 string par_text = pit->asString(*bv.buffer(), false);
440 for (int i = 0; i < lyxrc.label_init_length; ++i) {
441 if (par_text.empty())
444 par_text = split(par_text, head, ' ');
446 text += '-'; // Is it legal to use spaces in
455 // This function runs "configure" and then rereads lyx.defaults to
456 // reconfigure the automatic settings.
457 void Reconfigure(BufferView * bv)
459 bv->owner()->message(_("Running configure..."));
461 // Run configure in user lyx directory
462 Path p(user_lyxdir());
464 one.startscript(Systemcall::Wait,
465 AddName(system_lyxdir(), "configure"));
467 bv->owner()->message(_("Reloading configuration..."));
468 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
470 Alert::information(_("System reconfigured"),
471 _("The system has been reconfigured.\n"
472 "You need to restart LyX to make use of any \n"
473 "updated document class specifications."));