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;
72 using std::back_inserter;
79 using std::istream_iterator;
82 extern BufferList bufferlist;
83 // this should be static, but I need it in buffer.C
84 bool quitting; // flag, that we are quitting the program
91 bool MenuWrite(Buffer * buffer)
94 LyX::ref().lastfiles().newFile(buffer->fileName());
98 // FIXME: we don't tell the user *WHY* the save failed !!
100 string const file = MakeDisplayPath(buffer->fileName(), 30);
102 string text = bformat(_("The document %1$s could not be saved.\n\n"
103 "Do you want to rename the document and try again?"), file);
104 int const ret = Alert::prompt(_("Rename and save?"),
105 text, 0, 1, _("&Rename"), _("&Cancel"));
108 return WriteAs(buffer);
114 bool WriteAs(Buffer * buffer, string const & filename)
116 string fname = buffer->fileName();
117 string const oldname = fname;
119 if (filename.empty()) {
121 FileDialog fileDlg(_("Choose a filename to save document as"),
123 make_pair(string(_("Documents|#o#O")),
124 string(lyxrc.document_path)),
125 make_pair(string(_("Templates|#T#t")),
126 string(lyxrc.template_path)));
128 if (!IsLyXFilename(fname))
131 FileDialog::Result result =
132 fileDlg.save(OnlyPath(fname),
133 _("*.lyx| LyX Documents (*.lyx)"),
134 OnlyFilename(fname));
136 if (result.first == FileDialog::Later)
139 fname = result.second;
144 // Make sure the absolute filename ends with appropriate suffix
145 fname = MakeAbsPath(fname);
146 if (!IsLyXFilename(fname))
151 FileInfo const myfile(fname);
153 string const file = MakeDisplayPath(fname, 30);
154 string text = bformat(_("The document %1$s already exists.\n\n"
155 "Do you want to over-write that document?"), file);
156 int const ret = Alert::prompt(_("Over-write document?"),
157 text, 0, 1, _("&Over-write"), _("&Cancel"));
163 // Ok, change the name of the buffer
164 buffer->setFileName(fname);
166 bool unnamed = buffer->isUnnamed();
167 buffer->setUnnamed(false);
169 if (!MenuWrite(buffer)) {
170 buffer->setFileName(oldname);
171 buffer->setUnnamed(unnamed);
175 removeAutosaveFile(oldname);
182 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
184 if (lyx_gui::use_gui) {
185 if (!bufferlist.quitWriteAll())
188 LyX::cref().lastfiles().writeFile(lyxrc.lastfiles);
191 // Set a flag that we do quitting from the program,
192 // so no refreshes are necessary.
195 // close buffers first
196 bufferlist.closeAll();
198 // do any other cleanup procedures now
199 lyxerr[Debug::INFO] << "Deleting tmp dir " << os::getTmpDir() << endl;
201 if (destroyDir(os::getTmpDir()) != 0) {
202 string msg = bformat(_("Could not remove the temporary directory %1$s"),
204 Alert::warning(_("Could not remove temporary directory"), msg);
213 class AutoSaveBuffer : public ForkedProcess {
216 AutoSaveBuffer(BufferView & bv, string const & fname)
217 : bv_(bv), fname_(fname) {}
219 virtual auto_ptr<ForkedProcess> clone() const {
220 return auto_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
226 virtual int generateChild();
233 int AutoSaveBuffer::start()
235 command_ = bformat(_("Auto-saving %1$s"), fname_);
236 return runNonBlocking();
240 int AutoSaveBuffer::generateChild()
242 // tmp_ret will be located (usually) in /tmp
243 // will that be a problem?
244 pid_t const pid = fork(); // If you want to debug the autosave
245 // you should set pid to -1, and comment out the
247 if (pid == 0 || pid == -1) {
248 // pid = -1 signifies that lyx was unable
249 // to fork. But we will do the save
253 string const tmp_ret = tempName(string(), "lyxauto");
254 if (!tmp_ret.empty()) {
255 bv_.buffer()->writeFile(tmp_ret);
256 // assume successful write of tmp_ret
257 if (!rename(tmp_ret, fname_)) {
259 // most likely couldn't move between filesystems
260 // unless write of tmp_ret failed
261 // so remove tmp file (if it exists)
269 // failed to write/rename tmp_ret so try writing direct
270 if (!bv_.buffer()->writeFile(fname_)) {
271 // It is dangerous to do this in the child,
272 // but safe in the parent, so...
274 bv_.owner()->message(_("Autosave failed!"));
277 if (pid == 0) { // we are the child so...
287 void AutoSave(BufferView * bv)
288 // should probably be moved into BufferList (Lgb)
289 // Perfect target for a thread...
291 if (!bv->available())
294 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
295 // We don't save now, but we'll try again later
296 bv->owner()->resetAutosaveTimer();
300 bv->owner()->message(_("Autosaving current document..."));
302 // create autosave filename
303 string fname = bv->buffer()->filePath();
305 fname += OnlyFilename(bv->buffer()->fileName());
308 AutoSaveBuffer autosave(*bv, fname);
311 bv->buffer()->markBakClean();
312 bv->owner()->resetAutosaveTimer();
317 // Copyright CHT Software Service GmbH
320 // create new file with template
323 void NewFile(BufferView * bv, string const & filename)
325 // Split argument by :
327 string tmpname = split(filename, name, ':');
328 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
329 if (name.length() == 1
330 && isalpha(static_cast<unsigned char>(name[0]))
331 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
333 name += token(tmpname, ':', 0);
334 tmpname = split(tmpname, ':');
337 lyxerr[Debug::INFO] << "Arg is " << filename
338 << "\nName is " << name
339 << "\nTemplate is " << tmpname << endl;
341 bv->newFile(name, tmpname);
345 // Insert ascii file (if filename is empty, prompt for one)
346 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
348 if (!bv->available())
351 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
355 // clear the selection
356 if (bv->text() == bv->getLyXText())
357 bv->text()->clearSelection();
359 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
361 bv->getLyXText()->insertStringAsLines(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()->paragraphs();
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, ' ');
461 // Is it legal to use spaces in labels ?
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."));