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 "bufferlist.h"
21 #include "BufferView.h"
24 #include "lastfiles.h"
26 #include "lyxlayout.h"
29 #include "paragraph.h"
31 #include "frontends/Alert.h"
32 #include "frontends/FileDialog.h"
33 #include "frontends/lyx_gui.h"
34 #include "frontends/LyXView.h"
36 #include "support/FileInfo.h"
37 #include "support/filetools.h"
38 #include "support/forkedcall.h"
39 #include "support/lyxlib.h"
40 #include "support/os.h"
41 #include "support/path.h"
42 #include "support/path_defines.h"
43 #include "support/systemcall.h"
48 using lyx::support::AddName;
49 using lyx::support::bformat;
50 using lyx::support::destroyDir;
51 using lyx::support::FileInfo;
52 using lyx::support::ForkedProcess;
53 using lyx::support::IsLyXFilename;
54 using lyx::support::LibFileSearch;
55 using lyx::support::MakeAbsPath;
56 using lyx::support::MakeDisplayPath;
57 using lyx::support::OnlyFilename;
58 using lyx::support::OnlyPath;
59 using lyx::support::os;
60 using lyx::support::Path;
61 using lyx::support::removeAutosaveFile;
62 using lyx::support::rename;
63 using lyx::support::split;
64 using lyx::support::system_lyxdir;
65 using lyx::support::Systemcall;
66 using lyx::support::tempName;
67 using lyx::support::unlink;
68 using lyx::support::user_lyxdir;
70 using std::back_inserter;
77 using std::istream_iterator;
80 extern BufferList bufferlist;
81 // this should be static, but I need it in buffer.C
82 bool quitting; // flag, that we are quitting the program
89 bool MenuWrite(Buffer * buffer)
92 lastfiles->newFile(buffer->fileName());
96 // FIXME: we don't tell the user *WHY* the save failed !!
98 string const file = MakeDisplayPath(buffer->fileName(), 30);
100 string text = bformat(_("The document %1$s could not be saved.\n\n"
101 "Do you want to rename the document and try again?"), file);
102 int const ret = Alert::prompt(_("Rename and save?"),
103 text, 0, 1, _("&Rename"), _("&Cancel"));
106 return WriteAs(buffer);
112 bool WriteAs(Buffer * buffer, string const & filename)
114 string fname = buffer->fileName();
115 string const oldname = fname;
117 if (filename.empty()) {
119 FileDialog fileDlg(_("Choose a filename to save document as"),
121 make_pair(string(_("Documents|#o#O")),
122 string(lyxrc.document_path)),
123 make_pair(string(_("Templates|#T#t")),
124 string(lyxrc.template_path)));
126 if (!IsLyXFilename(fname))
129 FileDialog::Result result =
130 fileDlg.save(OnlyPath(fname),
131 _("*.lyx| LyX Documents (*.lyx)"),
132 OnlyFilename(fname));
134 if (result.first == FileDialog::Later)
137 fname = result.second;
142 // Make sure the absolute filename ends with appropriate suffix
143 fname = MakeAbsPath(fname);
144 if (!IsLyXFilename(fname))
149 FileInfo const myfile(fname);
151 string const file = MakeDisplayPath(fname, 30);
152 string text = bformat(_("The document %1$s already exists.\n\n"
153 "Do you want to over-write that document?"), file);
154 int const ret = Alert::prompt(_("Over-write document?"),
155 text, 0, 1, _("&Over-write"), _("&Cancel"));
161 // Ok, change the name of the buffer
162 buffer->setFileName(fname);
164 bool unnamed = buffer->isUnnamed();
165 buffer->setUnnamed(false);
167 if (!MenuWrite(buffer)) {
168 buffer->setFileName(oldname);
169 buffer->setUnnamed(unnamed);
173 removeAutosaveFile(oldname);
180 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
182 if (lyx_gui::use_gui) {
183 if (!bufferlist.quitWriteAll())
186 lastfiles->writeFile(lyxrc.lastfiles);
189 // Set a flag that we do quitting from the program,
190 // so no refreshes are necessary.
193 // close buffers first
194 bufferlist.closeAll();
196 // do any other cleanup procedures now
197 lyxerr[Debug::INFO] << "Deleting tmp dir " << os::getTmpDir() << endl;
199 if (destroyDir(os::getTmpDir()) != 0) {
200 string msg = bformat(_("Could not remove the temporary directory %1$s"),
202 Alert::warning(_("Could not remove temporary directory"), msg);
211 class AutoSaveBuffer : public ForkedProcess {
214 AutoSaveBuffer(BufferView & bv, string const & fname)
215 : bv_(bv), fname_(fname) {}
217 virtual ForkedProcess * clone() const {
218 return new AutoSaveBuffer(*this);
224 virtual int generateChild();
231 int AutoSaveBuffer::start()
233 command_ = bformat(_("Auto-saving %1$s"), fname_);
234 return runNonBlocking();
238 int AutoSaveBuffer::generateChild()
240 // tmp_ret will be located (usually) in /tmp
241 // will that be a problem?
242 pid_t const pid = fork(); // If you want to debug the autosave
243 // you should set pid to -1, and comment out the
245 if (pid == 0 || pid == -1) {
246 // pid = -1 signifies that lyx was unable
247 // to fork. But we will do the save
251 string const tmp_ret = tempName(string(), "lyxauto");
252 if (!tmp_ret.empty()) {
253 bv_.buffer()->writeFile(tmp_ret);
254 // assume successful write of tmp_ret
255 if (!rename(tmp_ret, fname_)) {
257 // most likely couldn't move between filesystems
258 // unless write of tmp_ret failed
259 // so remove tmp file (if it exists)
267 // failed to write/rename tmp_ret so try writing direct
268 if (!bv_.buffer()->writeFile(fname_)) {
269 // It is dangerous to do this in the child,
270 // but safe in the parent, so...
272 bv_.owner()->message(_("Autosave failed!"));
275 if (pid == 0) { // we are the child so...
285 void AutoSave(BufferView * bv)
286 // should probably be moved into BufferList (Lgb)
287 // Perfect target for a thread...
289 if (!bv->available())
292 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
293 // We don't save now, but we'll try again later
294 bv->owner()->resetAutosaveTimer();
298 bv->owner()->message(_("Autosaving current document..."));
300 // create autosave filename
301 string fname = bv->buffer()->filePath();
303 fname += OnlyFilename(bv->buffer()->fileName());
306 AutoSaveBuffer autosave(*bv, fname);
309 bv->buffer()->markBakClean();
310 bv->owner()->resetAutosaveTimer();
315 // Copyright CHT Software Service GmbH
318 // create new file with template
321 void NewFile(BufferView * bv, string const & filename)
323 // Split argument by :
325 string tmpname = split(filename, name, ':');
326 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
327 if (name.length() == 1
328 && isalpha(static_cast<unsigned char>(name[0]))
329 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
331 name += token(tmpname, ':', 0);
332 tmpname = split(tmpname, ':');
335 lyxerr[Debug::INFO] << "Arg is " << filename
336 << "\nName is " << name
337 << "\nTemplate is " << tmpname << endl;
339 bv->newFile(name, tmpname);
343 // Insert ascii file (if filename is empty, prompt for one)
344 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
346 if (!bv->available())
349 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
353 // clear the selection
354 bool flag = (bv->text == bv->getLyXText());
356 bv->beforeChange(bv->text);
358 bv->getLyXText()->insertStringAsLines(tmpstr);
360 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
365 // Insert ascii file (if filename is empty, prompt for one)
366 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
371 FileDialog fileDlg(_("Select file to insert"),
372 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
374 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
376 if (result.first == FileDialog::Later)
379 fname = result.second;
387 if (!fi.readable()) {
388 string const error = strerror(errno);
389 string const file = MakeDisplayPath(fname, 50);
390 string const text = bformat(_("Could not read the specified document\n"
391 "%1$s\ndue to the error: %2$s"), file, error);
392 Alert::error(_("Could not read file"), text);
396 ifstream ifs(fname.c_str());
398 string const error = strerror(errno);
399 string const file = MakeDisplayPath(fname, 50);
400 string const text = bformat(_("Could not open the specified document\n"
401 "%1$s\ndue to the error: %2$s"), file, error);
402 Alert::error(_("Could not open file"), text);
406 ifs.unsetf(ios::skipws);
407 istream_iterator<char> ii(ifs);
408 istream_iterator<char> end;
409 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
410 // We use this until the compilers get better...
411 std::vector<char> tmp;
412 copy(ii, end, back_inserter(tmp));
413 string const tmpstr(tmp.begin(), tmp.end());
415 // This is what we want to use and what we will use once the
416 // compilers get good enough.
417 //string tmpstr(ii, end); // yet a reason for using std::string
418 // alternate approach to get the file into a string:
420 copy(ii, end, back_inserter(tmpstr));
427 string const getPossibleLabel(BufferView const & bv)
429 ParagraphList::iterator pit = bv.getLyXText()->cursor.par();
430 ParagraphList & plist = bv.getLyXText()->ownerParagraphs();
432 LyXLayout_ptr layout = pit->layout();
434 if (layout->latextype == LATEX_PARAGRAPH && pit != plist.begin()) {
435 ParagraphList::iterator pit2 = boost::prior(pit);
437 LyXLayout_ptr const & layout2 = pit2->layout();
439 if (layout2->latextype != LATEX_PARAGRAPH) {
445 string text = layout->latexname().substr(0, 3);
446 if (layout->latexname() == "theorem")
447 text = "thm"; // Create a correct prefix for prettyref
450 if (layout->latextype == LATEX_PARAGRAPH ||
451 lyxrc.label_init_length < 0)
454 string par_text = pit->asString(*bv.buffer(), false);
455 for (int i = 0; i < lyxrc.label_init_length; ++i) {
456 if (par_text.empty())
459 par_text = split(par_text, head, ' ');
461 text += '-'; // Is it legal to use spaces in
470 // This function runs "configure" and then rereads lyx.defaults to
471 // reconfigure the automatic settings.
472 void Reconfigure(BufferView * bv)
474 bv->owner()->message(_("Running configure..."));
476 // Run configure in user lyx directory
477 Path p(user_lyxdir());
479 one.startscript(Systemcall::Wait,
480 AddName(system_lyxdir(), "configure"));
482 bv->owner()->message(_("Reloading configuration..."));
483 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
485 Alert::information(_("System reconfigured"),
486 _("The system has been reconfigured.\n"
487 "You need to restart LyX to make use of any \n"
488 "updated document class specifications."));