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::Path;
60 using lyx::support::removeAutosaveFile;
61 using lyx::support::rename;
62 using lyx::support::split;
63 using lyx::support::system_lyxdir;
64 using lyx::support::Systemcall;
65 using lyx::support::tempName;
66 using lyx::support::unlink;
67 using lyx::support::user_lyxdir;
69 namespace os = lyx::support::os;
71 using std::back_inserter;
78 using std::istream_iterator;
81 extern BufferList bufferlist;
82 // this should be static, but I need it in buffer.C
83 bool quitting; // flag, that we are quitting the program
90 bool MenuWrite(Buffer * buffer)
93 LyX::ref().lastfiles().newFile(buffer->fileName());
97 // FIXME: we don't tell the user *WHY* the save failed !!
99 string const file = MakeDisplayPath(buffer->fileName(), 30);
101 string text = bformat(_("The document %1$s could not be saved.\n\n"
102 "Do you want to rename the document and try again?"), file);
103 int const ret = Alert::prompt(_("Rename and save?"),
104 text, 0, 1, _("&Rename"), _("&Cancel"));
107 return WriteAs(buffer);
113 bool WriteAs(Buffer * buffer, string const & filename)
115 string fname = buffer->fileName();
116 string const oldname = fname;
118 if (filename.empty()) {
120 FileDialog fileDlg(_("Choose a filename to save document as"),
122 make_pair(string(_("Documents|#o#O")),
123 string(lyxrc.document_path)),
124 make_pair(string(_("Templates|#T#t")),
125 string(lyxrc.template_path)));
127 if (!IsLyXFilename(fname))
130 FileDialog::Result result =
131 fileDlg.save(OnlyPath(fname),
132 _("*.lyx| LyX Documents (*.lyx)"),
133 OnlyFilename(fname));
135 if (result.first == FileDialog::Later)
138 fname = result.second;
143 // Make sure the absolute filename ends with appropriate suffix
144 fname = MakeAbsPath(fname);
145 if (!IsLyXFilename(fname))
150 FileInfo const myfile(fname);
152 string const file = MakeDisplayPath(fname, 30);
153 string text = bformat(_("The document %1$s already exists.\n\n"
154 "Do you want to over-write that document?"), file);
155 int const ret = Alert::prompt(_("Over-write document?"),
156 text, 0, 1, _("&Over-write"), _("&Cancel"));
162 // Ok, change the name of the buffer
163 buffer->setFileName(fname);
165 bool unnamed = buffer->isUnnamed();
166 buffer->setUnnamed(false);
168 if (!MenuWrite(buffer)) {
169 buffer->setFileName(oldname);
170 buffer->setUnnamed(unnamed);
174 removeAutosaveFile(oldname);
181 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
183 if (lyx_gui::use_gui) {
184 if (!bufferlist.quitWriteAll())
187 LyX::cref().lastfiles().writeFile(lyxrc.lastfiles);
190 // Set a flag that we do quitting from the program,
191 // so no refreshes are necessary.
194 // close buffers first
195 bufferlist.closeAll();
197 // do any other cleanup procedures now
198 lyxerr[Debug::INFO] << "Deleting tmp dir " << os::getTmpDir() << endl;
200 if (destroyDir(os::getTmpDir()) != 0) {
201 string msg = bformat(_("Could not remove the temporary directory %1$s"),
203 Alert::warning(_("Could not remove temporary directory"), msg);
212 class AutoSaveBuffer : public ForkedProcess {
215 AutoSaveBuffer(BufferView & bv, string const & fname)
216 : bv_(bv), fname_(fname) {}
218 virtual ForkedProcess * clone() const {
219 return new AutoSaveBuffer(*this);
225 virtual int generateChild();
232 int AutoSaveBuffer::start()
234 command_ = bformat(_("Auto-saving %1$s"), fname_);
235 return runNonBlocking();
239 int AutoSaveBuffer::generateChild()
241 // tmp_ret will be located (usually) in /tmp
242 // will that be a problem?
243 pid_t const pid = fork(); // If you want to debug the autosave
244 // you should set pid to -1, and comment out the
246 if (pid == 0 || pid == -1) {
247 // pid = -1 signifies that lyx was unable
248 // to fork. But we will do the save
252 string const tmp_ret = tempName(string(), "lyxauto");
253 if (!tmp_ret.empty()) {
254 bv_.buffer()->writeFile(tmp_ret);
255 // assume successful write of tmp_ret
256 if (!rename(tmp_ret, fname_)) {
258 // most likely couldn't move between filesystems
259 // unless write of tmp_ret failed
260 // so remove tmp file (if it exists)
268 // failed to write/rename tmp_ret so try writing direct
269 if (!bv_.buffer()->writeFile(fname_)) {
270 // It is dangerous to do this in the child,
271 // but safe in the parent, so...
273 bv_.owner()->message(_("Autosave failed!"));
276 if (pid == 0) { // we are the child so...
286 void AutoSave(BufferView * bv)
287 // should probably be moved into BufferList (Lgb)
288 // Perfect target for a thread...
290 if (!bv->available())
293 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
294 // We don't save now, but we'll try again later
295 bv->owner()->resetAutosaveTimer();
299 bv->owner()->message(_("Autosaving current document..."));
301 // create autosave filename
302 string fname = bv->buffer()->filePath();
304 fname += OnlyFilename(bv->buffer()->fileName());
307 AutoSaveBuffer autosave(*bv, fname);
310 bv->buffer()->markBakClean();
311 bv->owner()->resetAutosaveTimer();
316 // Copyright CHT Software Service GmbH
319 // create new file with template
322 void NewFile(BufferView * bv, string const & filename)
324 // Split argument by :
326 string tmpname = split(filename, name, ':');
327 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
328 if (name.length() == 1
329 && isalpha(static_cast<unsigned char>(name[0]))
330 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
332 name += token(tmpname, ':', 0);
333 tmpname = split(tmpname, ':');
336 lyxerr[Debug::INFO] << "Arg is " << filename
337 << "\nName is " << name
338 << "\nTemplate is " << tmpname << endl;
340 bv->newFile(name, tmpname);
344 // Insert ascii file (if filename is empty, prompt for one)
345 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
347 if (!bv->available())
350 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
354 // clear the selection
355 bool flag = (bv->text == bv->getLyXText());
357 bv->beforeChange(bv->text);
359 bv->getLyXText()->insertStringAsLines(tmpstr);
361 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
366 // Insert ascii file (if filename is empty, prompt for one)
367 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
372 FileDialog fileDlg(_("Select file to insert"),
373 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
375 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
377 if (result.first == FileDialog::Later)
380 fname = result.second;
388 if (!fi.readable()) {
389 string const error = strerror(errno);
390 string const file = MakeDisplayPath(fname, 50);
391 string const text = bformat(_("Could not read the specified document\n"
392 "%1$s\ndue to the error: %2$s"), file, error);
393 Alert::error(_("Could not read file"), text);
397 ifstream ifs(fname.c_str());
399 string const error = strerror(errno);
400 string const file = MakeDisplayPath(fname, 50);
401 string const text = bformat(_("Could not open the specified document\n"
402 "%1$s\ndue to the error: %2$s"), file, error);
403 Alert::error(_("Could not open file"), text);
407 ifs.unsetf(ios::skipws);
408 istream_iterator<char> ii(ifs);
409 istream_iterator<char> end;
410 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
411 // We use this until the compilers get better...
412 std::vector<char> tmp;
413 copy(ii, end, back_inserter(tmp));
414 string const tmpstr(tmp.begin(), tmp.end());
416 // This is what we want to use and what we will use once the
417 // compilers get good enough.
418 //string tmpstr(ii, end); // yet a reason for using std::string
419 // alternate approach to get the file into a string:
421 copy(ii, end, back_inserter(tmpstr));
428 string const getPossibleLabel(BufferView const & bv)
430 ParagraphList::iterator pit = bv.getLyXText()->cursorPar();
431 ParagraphList & plist = bv.getLyXText()->ownerParagraphs();
433 LyXLayout_ptr layout = pit->layout();
435 if (layout->latextype == LATEX_PARAGRAPH && pit != plist.begin()) {
436 ParagraphList::iterator pit2 = boost::prior(pit);
438 LyXLayout_ptr const & layout2 = pit2->layout();
440 if (layout2->latextype != LATEX_PARAGRAPH) {
446 string text = layout->latexname().substr(0, 3);
447 if (layout->latexname() == "theorem")
448 text = "thm"; // Create a correct prefix for prettyref
451 if (layout->latextype == LATEX_PARAGRAPH ||
452 lyxrc.label_init_length < 0)
455 string par_text = pit->asString(*bv.buffer(), false);
456 for (int i = 0; i < lyxrc.label_init_length; ++i) {
457 if (par_text.empty())
460 par_text = split(par_text, head, ' ');
462 text += '-'; // Is it legal to use spaces in
471 // This function runs "configure" and then rereads lyx.defaults to
472 // reconfigure the automatic settings.
473 void Reconfigure(BufferView * bv)
475 bv->owner()->message(_("Running configure..."));
477 // Run configure in user lyx directory
478 Path p(user_lyxdir());
480 one.startscript(Systemcall::Wait,
481 AddName(system_lyxdir(), "configure"));
483 bv->owner()->message(_("Reloading configuration..."));
484 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
486 Alert::information(_("System reconfigured"),
487 _("The system has been reconfigured.\n"
488 "You need to restart LyX to make use of any \n"
489 "updated document class specifications."));