1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich,
7 * Copyright 1995-2001 The LyX Team.
9 * ====================================================== */
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferview_funcs.h"
20 #include "lastfiles.h"
24 #include "BufferView.h"
27 #include "insets/insetlabel.h"
29 #include "frontends/lyx_gui.h"
30 #include "frontends/LyXView.h"
31 #include "frontends/Alert.h"
32 #include "frontends/FileDialog.h"
34 #include "support/FileInfo.h"
35 #include "support/filetools.h"
36 #include "support/forkedcall.h"
37 #include "support/path.h"
38 #include "support/path_defines.h"
39 #include "support/systemcall.h"
40 #include "support/lstrings.h"
47 using namespace lyx::support;
54 using std::back_inserter;
55 using std::istream_iterator;
59 extern BufferList bufferlist;
60 // this should be static, but I need it in buffer.C
61 bool quitting; // flag, that we are quitting the program
68 bool MenuWrite(Buffer * buffer)
71 lastfiles->newFile(buffer->fileName());
75 // FIXME: we don't tell the user *WHY* the save failed !!
77 string const file = MakeDisplayPath(buffer->fileName(), 30);
79 string text = bformat(_("The document %1$s could not be saved.\n\n"
80 "Do you want to rename the document and try again?"), file);
81 int const ret = Alert::prompt(_("Rename and save?"),
82 text, 0, 1, _("&Rename"), _("&Cancel"));
85 return WriteAs(buffer);
91 bool WriteAs(Buffer * buffer, string const & filename)
93 string fname = buffer->fileName();
94 string const oldname = fname;
96 if (filename.empty()) {
98 FileDialog fileDlg(_("Choose a filename to save document as"),
100 make_pair(string(_("Documents|#o#O")),
101 string(lyxrc.document_path)),
102 make_pair(string(_("Templates|#T#t")),
103 string(lyxrc.template_path)));
105 if (!IsLyXFilename(fname))
108 FileDialog::Result result =
109 fileDlg.save(OnlyPath(fname),
110 _("*.lyx| LyX Documents (*.lyx)"),
111 OnlyFilename(fname));
113 if (result.first == FileDialog::Later)
116 fname = result.second;
121 // Make sure the absolute filename ends with appropriate suffix
122 fname = MakeAbsPath(fname);
123 if (!IsLyXFilename(fname))
128 FileInfo const myfile(fname);
130 string const file = MakeDisplayPath(fname, 30);
131 string text = bformat(_("The document %1$s already exists.\n\n"
132 "Do you want to over-write that document?"), file);
133 int const ret = Alert::prompt(_("Over-write document?"),
134 text, 0, 1, _("&Over-write"), _("&Cancel"));
140 // Ok, change the name of the buffer
141 buffer->setFileName(fname);
143 bool unnamed = buffer->isUnnamed();
144 buffer->setUnnamed(false);
146 if (!MenuWrite(buffer)) {
147 buffer->setFileName(oldname);
148 buffer->setUnnamed(unnamed);
152 removeAutosaveFile(oldname);
159 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
161 if (lyx_gui::use_gui) {
162 if (!bufferlist.quitWriteAll())
165 lastfiles->writeFile(lyxrc.lastfiles);
168 // Set a flag that we do quitting from the program,
169 // so no refreshes are necessary.
172 // close buffers first
173 bufferlist.closeAll();
175 // do any other cleanup procedures now
176 lyxerr[Debug::INFO] << "Deleting tmp dir " << os::getTmpDir() << endl;
178 if (destroyDir(os::getTmpDir()) != 0) {
179 string msg = bformat(_("Could not remove the temporary directory %1$s"),
181 Alert::warning(_("Could not remove temporary directory"), msg);
190 class AutoSaveBuffer : public ForkedProcess {
193 AutoSaveBuffer(BufferView & bv, string const & fname)
194 : bv_(bv), fname_(fname) {}
196 virtual ForkedProcess * clone() const {
197 return new AutoSaveBuffer(*this);
203 virtual int generateChild();
210 int AutoSaveBuffer::start()
212 command_ = bformat(_("Auto-saving %1$s"), fname_);
213 return runNonBlocking();
217 int AutoSaveBuffer::generateChild()
219 // tmp_ret will be located (usually) in /tmp
220 // will that be a problem?
221 pid_t const pid = fork(); // If you want to debug the autosave
222 // you should set pid to -1, and comment out the
224 if (pid == 0 || pid == -1) {
225 // pid = -1 signifies that lyx was unable
226 // to fork. But we will do the save
230 string const tmp_ret = tempName(string(), "lyxauto");
231 if (!tmp_ret.empty()) {
232 bv_.buffer()->writeFile(tmp_ret);
233 // assume successful write of tmp_ret
234 if (!rename(tmp_ret, fname_)) {
236 // most likely couldn't move between filesystems
237 // unless write of tmp_ret failed
238 // so remove tmp file (if it exists)
246 // failed to write/rename tmp_ret so try writing direct
247 if (!bv_.buffer()->writeFile(fname_)) {
248 // It is dangerous to do this in the child,
249 // but safe in the parent, so...
251 bv_.owner()->message(_("Autosave failed!"));
254 if (pid == 0) { // we are the child so...
264 void AutoSave(BufferView * bv)
265 // should probably be moved into BufferList (Lgb)
266 // Perfect target for a thread...
268 if (!bv->available())
271 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
272 // We don't save now, but we'll try again later
273 bv->owner()->resetAutosaveTimer();
277 bv->owner()->message(_("Autosaving current document..."));
279 // create autosave filename
280 string fname = bv->buffer()->filePath();
282 fname += OnlyFilename(bv->buffer()->fileName());
285 AutoSaveBuffer autosave(*bv, fname);
288 bv->buffer()->markBakClean();
289 bv->owner()->resetAutosaveTimer();
294 // Copyright CHT Software Service GmbH
297 // create new file with template
300 void NewFile(BufferView * bv, string const & filename)
302 // Split argument by :
304 string tmpname = split(filename, name, ':');
305 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
306 if (name.length() == 1
307 && isalpha(static_cast<unsigned char>(name[0]))
308 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
310 name += token(tmpname, ':', 0);
311 tmpname = split(tmpname, ':');
314 lyxerr[Debug::INFO] << "Arg is " << filename
315 << "\nName is " << name
316 << "\nTemplate is " << tmpname << endl;
318 bv->newFile(name, tmpname);
322 // Insert ascii file (if filename is empty, prompt for one)
323 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
325 if (!bv->available())
328 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
332 // clear the selection
333 bool flag = (bv->text == bv->getLyXText());
335 bv->beforeChange(bv->text);
337 bv->getLyXText()->insertStringAsLines(tmpstr);
339 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
344 // Insert ascii file (if filename is empty, prompt for one)
345 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
350 FileDialog fileDlg(_("Select file to insert"),
351 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
353 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
355 if (result.first == FileDialog::Later)
358 fname = result.second;
366 if (!fi.readable()) {
367 string const error = strerror(errno);
368 string const file = MakeDisplayPath(fname, 50);
369 string const text = bformat(_("Could not read the specified document\n"
370 "%1$s\ndue to the error: %2$s"), file, error);
371 Alert::error(_("Could not read file"), text);
375 ifstream ifs(fname.c_str());
377 string const error = strerror(errno);
378 string const file = MakeDisplayPath(fname, 50);
379 string const text = bformat(_("Could not open the specified document\n"
380 "%1$s\ndue to the error: %2$s"), file, error);
381 Alert::error(_("Could not open file"), text);
385 ifs.unsetf(ios::skipws);
386 istream_iterator<char> ii(ifs);
387 istream_iterator<char> end;
388 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
389 // We use this until the compilers get better...
391 copy(ii, end, back_inserter(tmp));
392 string const tmpstr(tmp.begin(), tmp.end());
394 // This is what we want to use and what we will use once the
395 // compilers get good enough.
396 //string tmpstr(ii, end); // yet a reason for using std::string
397 // alternate approach to get the file into a string:
399 copy(ii, end, back_inserter(tmpstr));
406 string const getPossibleLabel(BufferView const & bv)
408 ParagraphList::iterator pit = bv.getLyXText()->cursor.par();
409 ParagraphList & plist = bv.getLyXText()->ownerParagraphs();
411 LyXLayout_ptr layout = pit->layout();
413 if (layout->latextype == LATEX_PARAGRAPH && pit != plist.begin()) {
414 ParagraphList::iterator pit2 = boost::prior(pit);
416 LyXLayout_ptr const & layout2 = pit2->layout();
418 if (layout2->latextype != LATEX_PARAGRAPH) {
424 string text = layout->latexname().substr(0, 3);
425 if (layout->latexname() == "theorem")
426 text = "thm"; // Create a correct prefix for prettyref
429 if (layout->latextype == LATEX_PARAGRAPH ||
430 lyxrc.label_init_length < 0)
433 string par_text = pit->asString(bv.buffer(), false);
434 for (int i = 0; i < lyxrc.label_init_length; ++i) {
435 if (par_text.empty())
438 par_text = split(par_text, head, ' ');
440 text += '-'; // Is it legal to use spaces in
449 // This function runs "configure" and then rereads lyx.defaults to
450 // reconfigure the automatic settings.
451 void Reconfigure(BufferView * bv)
453 bv->owner()->message(_("Running configure..."));
455 // Run configure in user lyx directory
456 Path p(user_lyxdir());
458 one.startscript(Systemcall::Wait,
459 AddName(system_lyxdir(), "configure"));
461 bv->owner()->message(_("Reloading configuration..."));
462 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
464 Alert::information(_("System reconfigured"),
465 _("The system has been reconfigured.\n"
466 "You need to restart LyX to make use of any \n"
467 "updated document class specifications."));