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/path.h"
42 #include "support/path_defines.h"
43 #include "support/systemcall.h"
44 #include "support/lstrings.h"
51 using namespace lyx::support;
58 using std::back_inserter;
59 using std::istream_iterator;
63 extern BufferList bufferlist;
64 // this should be static, but I need it in buffer.C
65 bool quitting; // flag, that we are quitting the program
72 bool MenuWrite(Buffer * buffer)
75 lastfiles->newFile(buffer->fileName());
79 // FIXME: we don't tell the user *WHY* the save failed !!
81 string const file = MakeDisplayPath(buffer->fileName(), 30);
83 string text = bformat(_("The document %1$s could not be saved.\n\n"
84 "Do you want to rename the document and try again?"), file);
85 int const ret = Alert::prompt(_("Rename and save?"),
86 text, 0, 1, _("&Rename"), _("&Cancel"));
89 return WriteAs(buffer);
95 bool WriteAs(Buffer * buffer, string const & filename)
97 string fname = buffer->fileName();
98 string const oldname = fname;
100 if (filename.empty()) {
102 FileDialog fileDlg(_("Choose a filename to save document as"),
104 make_pair(string(_("Documents|#o#O")),
105 string(lyxrc.document_path)),
106 make_pair(string(_("Templates|#T#t")),
107 string(lyxrc.template_path)));
109 if (!IsLyXFilename(fname))
112 FileDialog::Result result =
113 fileDlg.save(OnlyPath(fname),
114 _("*.lyx| LyX Documents (*.lyx)"),
115 OnlyFilename(fname));
117 if (result.first == FileDialog::Later)
120 fname = result.second;
125 // Make sure the absolute filename ends with appropriate suffix
126 fname = MakeAbsPath(fname);
127 if (!IsLyXFilename(fname))
132 FileInfo const myfile(fname);
134 string const file = MakeDisplayPath(fname, 30);
135 string text = bformat(_("The document %1$s already exists.\n\n"
136 "Do you want to over-write that document?"), file);
137 int const ret = Alert::prompt(_("Over-write document?"),
138 text, 0, 1, _("&Over-write"), _("&Cancel"));
144 // Ok, change the name of the buffer
145 buffer->setFileName(fname);
147 bool unnamed = buffer->isUnnamed();
148 buffer->setUnnamed(false);
150 if (!MenuWrite(buffer)) {
151 buffer->setFileName(oldname);
152 buffer->setUnnamed(unnamed);
156 removeAutosaveFile(oldname);
163 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
165 if (lyx_gui::use_gui) {
166 if (!bufferlist.quitWriteAll())
169 lastfiles->writeFile(lyxrc.lastfiles);
172 // Set a flag that we do quitting from the program,
173 // so no refreshes are necessary.
176 // close buffers first
177 bufferlist.closeAll();
179 // do any other cleanup procedures now
180 lyxerr[Debug::INFO] << "Deleting tmp dir " << os::getTmpDir() << endl;
182 if (destroyDir(os::getTmpDir()) != 0) {
183 string msg = bformat(_("Could not remove the temporary directory %1$s"),
185 Alert::warning(_("Could not remove temporary directory"), msg);
194 class AutoSaveBuffer : public ForkedProcess {
197 AutoSaveBuffer(BufferView & bv, string const & fname)
198 : bv_(bv), fname_(fname) {}
200 virtual ForkedProcess * clone() const {
201 return new AutoSaveBuffer(*this);
207 virtual int generateChild();
214 int AutoSaveBuffer::start()
216 command_ = bformat(_("Auto-saving %1$s"), fname_);
217 return runNonBlocking();
221 int AutoSaveBuffer::generateChild()
223 // tmp_ret will be located (usually) in /tmp
224 // will that be a problem?
225 pid_t const pid = fork(); // If you want to debug the autosave
226 // you should set pid to -1, and comment out the
228 if (pid == 0 || pid == -1) {
229 // pid = -1 signifies that lyx was unable
230 // to fork. But we will do the save
234 string const tmp_ret = tempName(string(), "lyxauto");
235 if (!tmp_ret.empty()) {
236 bv_.buffer()->writeFile(tmp_ret);
237 // assume successful write of tmp_ret
238 if (!rename(tmp_ret, fname_)) {
240 // most likely couldn't move between filesystems
241 // unless write of tmp_ret failed
242 // so remove tmp file (if it exists)
250 // failed to write/rename tmp_ret so try writing direct
251 if (!bv_.buffer()->writeFile(fname_)) {
252 // It is dangerous to do this in the child,
253 // but safe in the parent, so...
255 bv_.owner()->message(_("Autosave failed!"));
258 if (pid == 0) { // we are the child so...
268 void AutoSave(BufferView * bv)
269 // should probably be moved into BufferList (Lgb)
270 // Perfect target for a thread...
272 if (!bv->available())
275 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
276 // We don't save now, but we'll try again later
277 bv->owner()->resetAutosaveTimer();
281 bv->owner()->message(_("Autosaving current document..."));
283 // create autosave filename
284 string fname = bv->buffer()->filePath();
286 fname += OnlyFilename(bv->buffer()->fileName());
289 AutoSaveBuffer autosave(*bv, fname);
292 bv->buffer()->markBakClean();
293 bv->owner()->resetAutosaveTimer();
298 // Copyright CHT Software Service GmbH
301 // create new file with template
304 void NewFile(BufferView * bv, string const & filename)
306 // Split argument by :
308 string tmpname = split(filename, name, ':');
309 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
310 if (name.length() == 1
311 && isalpha(static_cast<unsigned char>(name[0]))
312 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
314 name += token(tmpname, ':', 0);
315 tmpname = split(tmpname, ':');
318 lyxerr[Debug::INFO] << "Arg is " << filename
319 << "\nName is " << name
320 << "\nTemplate is " << tmpname << endl;
322 bv->newFile(name, tmpname);
326 // Insert ascii file (if filename is empty, prompt for one)
327 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
329 if (!bv->available())
332 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
336 // clear the selection
337 bool flag = (bv->text == bv->getLyXText());
339 bv->beforeChange(bv->text);
341 bv->getLyXText()->insertStringAsLines(tmpstr);
343 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
348 // Insert ascii file (if filename is empty, prompt for one)
349 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
354 FileDialog fileDlg(_("Select file to insert"),
355 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
357 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
359 if (result.first == FileDialog::Later)
362 fname = result.second;
370 if (!fi.readable()) {
371 string const error = strerror(errno);
372 string const file = MakeDisplayPath(fname, 50);
373 string const text = bformat(_("Could not read the specified document\n"
374 "%1$s\ndue to the error: %2$s"), file, error);
375 Alert::error(_("Could not read file"), text);
379 ifstream ifs(fname.c_str());
381 string const error = strerror(errno);
382 string const file = MakeDisplayPath(fname, 50);
383 string const text = bformat(_("Could not open the specified document\n"
384 "%1$s\ndue to the error: %2$s"), file, error);
385 Alert::error(_("Could not open file"), text);
389 ifs.unsetf(ios::skipws);
390 istream_iterator<char> ii(ifs);
391 istream_iterator<char> end;
392 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
393 // We use this until the compilers get better...
395 copy(ii, end, back_inserter(tmp));
396 string const tmpstr(tmp.begin(), tmp.end());
398 // This is what we want to use and what we will use once the
399 // compilers get good enough.
400 //string tmpstr(ii, end); // yet a reason for using std::string
401 // alternate approach to get the file into a string:
403 copy(ii, end, back_inserter(tmpstr));
410 string const getPossibleLabel(BufferView const & bv)
412 ParagraphList::iterator pit = bv.getLyXText()->cursor.par();
413 ParagraphList & plist = bv.getLyXText()->ownerParagraphs();
415 LyXLayout_ptr layout = pit->layout();
417 if (layout->latextype == LATEX_PARAGRAPH && pit != plist.begin()) {
418 ParagraphList::iterator pit2 = boost::prior(pit);
420 LyXLayout_ptr const & layout2 = pit2->layout();
422 if (layout2->latextype != LATEX_PARAGRAPH) {
428 string text = layout->latexname().substr(0, 3);
429 if (layout->latexname() == "theorem")
430 text = "thm"; // Create a correct prefix for prettyref
433 if (layout->latextype == LATEX_PARAGRAPH ||
434 lyxrc.label_init_length < 0)
437 string par_text = pit->asString(*bv.buffer(), false);
438 for (int i = 0; i < lyxrc.label_init_length; ++i) {
439 if (par_text.empty())
442 par_text = split(par_text, head, ' ');
444 text += '-'; // Is it legal to use spaces in
453 // This function runs "configure" and then rereads lyx.defaults to
454 // reconfigure the automatic settings.
455 void Reconfigure(BufferView * bv)
457 bv->owner()->message(_("Running configure..."));
459 // Run configure in user lyx directory
460 Path p(user_lyxdir());
462 one.startscript(Systemcall::Wait,
463 AddName(system_lyxdir(), "configure"));
465 bv->owner()->message(_("Reloading configuration..."));
466 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
468 Alert::information(_("System reconfigured"),
469 _("The system has been reconfigured.\n"
470 "You need to restart LyX to make use of any \n"
471 "updated document class specifications."));