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/systemcall.h"
39 #include "support/lstrings.h"
51 using std::back_inserter;
52 using std::istream_iterator;
56 extern BufferList bufferlist;
57 // this should be static, but I need it in buffer.C
58 bool quitting; // flag, that we are quitting the program
61 void ShowMessage(Buffer const * buf,
67 && buf && buf->getUser() && buf->getUser()->owner()) {
68 string const str = msg1 + ' ' + msg2 + ' ' + msg3;
69 buf->getUser()->owner()->message(str);
71 lyxerr << msg1 << msg2 << msg3 << endl;
79 bool MenuWrite(Buffer * buffer)
82 lastfiles->newFile(buffer->fileName());
86 // FIXME: we don't tell the user *WHY* the save failed !!
88 string const file = MakeDisplayPath(buffer->fileName(), 30);
90 string text = bformat(_("The document %1$s could not be saved.\n\n"
91 "Do you want to rename the document and try again?"), file);
92 int const ret = Alert::prompt(_("Rename and save?"),
93 text, 0, 1, _("&Rename"), _("&Cancel"));
96 return WriteAs(buffer);
102 bool WriteAs(Buffer * buffer, string const & filename)
104 string fname = buffer->fileName();
105 string const oldname = fname;
107 if (filename.empty()) {
109 FileDialog fileDlg(_("Choose a filename to save document as"),
111 make_pair(string(_("Documents|#o#O")),
112 string(lyxrc.document_path)),
113 make_pair(string(_("Templates|#T#t")),
114 string(lyxrc.template_path)));
116 if (!IsLyXFilename(fname))
119 FileDialog::Result result =
120 fileDlg.save(OnlyPath(fname),
121 _("*.lyx| LyX Documents (*.lyx)"),
122 OnlyFilename(fname));
124 if (result.first == FileDialog::Later)
127 fname = result.second;
132 // Make sure the absolute filename ends with appropriate suffix
133 fname = MakeAbsPath(fname);
134 if (!IsLyXFilename(fname))
139 FileInfo const myfile(fname);
141 string const file = MakeDisplayPath(fname, 30);
142 string text = bformat(_("The document %1$s already exists.\n\n"
143 "Do you want to over-write that document?"), file);
144 int const ret = Alert::prompt(_("Over-write document?"),
145 text, 0, 1, _("&Over-write"), _("&Cancel"));
151 // Ok, change the name of the buffer
152 buffer->setFileName(fname);
154 bool unnamed = buffer->isUnnamed();
155 buffer->setUnnamed(false);
157 if (!MenuWrite(buffer)) {
158 buffer->setFileName(oldname);
159 buffer->setUnnamed(unnamed);
163 removeAutosaveFile(oldname);
170 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
172 if (lyx_gui::use_gui) {
173 if (!bufferlist.quitWriteAll())
176 lastfiles->writeFile(lyxrc.lastfiles);
179 // Set a flag that we do quitting from the program,
180 // so no refreshes are necessary.
183 // close buffers first
184 bufferlist.closeAll();
186 // do any other cleanup procedures now
187 lyxerr[Debug::INFO] << "Deleting tmp dir " << system_tempdir << endl;
189 if (destroyDir(system_tempdir) != 0) {
190 string msg = bformat(_("Could not remove the temporary directory %1$s"),
192 Alert::warning(_("Could not remove temporary directory"), msg);
201 class AutoSaveBuffer : public ForkedProcess {
204 AutoSaveBuffer(BufferView & bv, string const & fname)
205 : bv_(bv), fname_(fname) {}
207 virtual ForkedProcess * clone() const {
208 return new AutoSaveBuffer(*this);
214 virtual int generateChild();
221 int AutoSaveBuffer::start()
223 command_ = bformat(_("Auto-saving %1$s"), fname_);
224 return runNonBlocking();
228 int AutoSaveBuffer::generateChild()
230 // tmp_ret will be located (usually) in /tmp
231 // will that be a problem?
232 pid_t const pid = fork(); // If you want to debug the autosave
233 // you should set pid to -1, and comment out the
235 if (pid == 0 || pid == -1) {
236 // pid = -1 signifies that lyx was unable
237 // to fork. But we will do the save
241 string const tmp_ret = lyx::tempName(string(), "lyxauto");
242 if (!tmp_ret.empty()) {
243 bv_.buffer()->writeFile(tmp_ret);
244 // assume successful write of tmp_ret
245 if (!lyx::rename(tmp_ret, fname_)) {
247 // most likely couldn't move between filesystems
248 // unless write of tmp_ret failed
249 // so remove tmp file (if it exists)
250 lyx::unlink(tmp_ret);
257 // failed to write/rename tmp_ret so try writing direct
258 if (!bv_.buffer()->writeFile(fname_)) {
259 // It is dangerous to do this in the child,
260 // but safe in the parent, so...
262 bv_.owner()->message(_("Autosave failed!"));
265 if (pid == 0) { // we are the child so...
275 void AutoSave(BufferView * bv)
276 // should probably be moved into BufferList (Lgb)
277 // Perfect target for a thread...
279 if (!bv->available())
282 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
283 // We don't save now, but we'll try again later
284 bv->owner()->resetAutosaveTimer();
288 bv->owner()->message(_("Autosaving current document..."));
290 // create autosave filename
291 string fname = bv->buffer()->filePath();
293 fname += OnlyFilename(bv->buffer()->fileName());
296 AutoSaveBuffer autosave(*bv, fname);
299 bv->buffer()->markBakClean();
300 bv->owner()->resetAutosaveTimer();
305 // Copyright CHT Software Service GmbH
308 // create new file with template
311 Buffer * NewFile(string const & filename)
313 // Split argument by :
315 string tmpname = split(filename, name, ':');
316 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
317 if (name.length() == 1
318 && isalpha(static_cast<unsigned char>(name[0]))
319 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
321 name += token(tmpname, ':', 0);
322 tmpname = split(tmpname, ':');
325 lyxerr[Debug::INFO] << "Arg is " << filename
326 << "\nName is " << name
327 << "\nTemplate is " << tmpname << endl;
329 // find a free buffer
330 Buffer * tmpbuf = newFile(name, tmpname);
332 lastfiles->newFile(tmpbuf->fileName());
337 // Insert ascii file (if filename is empty, prompt for one)
338 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
340 if (!bv->available())
343 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
347 // clear the selection
348 bool flag = (bv->text == bv->getLyXText());
350 bv->beforeChange(bv->text);
352 bv->getLyXText()->insertStringAsLines(tmpstr);
354 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
356 bv->update(BufferView::SELECT);
360 // Insert ascii file (if filename is empty, prompt for one)
361 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
366 FileDialog fileDlg(_("Select file to insert"),
367 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
369 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
371 if (result.first == FileDialog::Later)
374 fname = result.second;
382 if (!fi.readable()) {
383 string const error = strerror(errno);
384 string const file = MakeDisplayPath(fname, 50);
385 string const text = bformat(_("Could not read the specified document\n"
386 "%1$s\ndue to the error: %2$s"), file, error);
387 Alert::error(_("Could not read file"), text);
391 ifstream ifs(fname.c_str());
393 string const error = strerror(errno);
394 string const file = MakeDisplayPath(fname, 50);
395 string const text = bformat(_("Could not open the specified document\n"
396 "%1$s\ndue to the error: %2$s"), file, error);
397 Alert::error(_("Could not open file"), text);
401 ifs.unsetf(ios::skipws);
402 istream_iterator<char> ii(ifs);
403 istream_iterator<char> end;
404 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
405 // We use this until the compilers get better...
407 copy(ii, end, back_inserter(tmp));
408 string const tmpstr(tmp.begin(), tmp.end());
410 // This is what we want to use and what we will use once the
411 // compilers get good enough.
412 //string tmpstr(ii, end); // yet a reason for using std::string
413 // alternate approach to get the file into a string:
415 copy(ii, end, back_inserter(tmpstr));
422 string const getPossibleLabel(BufferView const & bv)
424 ParagraphList::iterator pit = bv.getLyXText()->cursor.par();
425 ParagraphList & plist = bv.getLyXText()->ownerParagraphs();
427 LyXLayout_ptr layout = pit->layout();
429 if (layout->latextype == LATEX_PARAGRAPH && pit != plist.begin()) {
430 ParagraphList::iterator pit2 = boost::prior(pit);
432 LyXLayout_ptr const & layout2 = pit2->layout();
434 if (layout2->latextype != LATEX_PARAGRAPH) {
440 string text = layout->latexname().substr(0, 3);
441 if (layout->latexname() == "theorem")
442 text = "thm"; // Create a correct prefix for prettyref
445 if (layout->latextype == LATEX_PARAGRAPH ||
446 lyxrc.label_init_length < 0)
449 string par_text = pit->asString(bv.buffer(), false);
450 for (int i = 0; i < lyxrc.label_init_length; ++i) {
451 if (par_text.empty())
454 par_text = split(par_text, head, ' ');
456 text += '-'; // Is it legal to use spaces in
465 // This function runs "configure" and then rereads lyx.defaults to
466 // reconfigure the automatic settings.
467 void Reconfigure(BufferView * bv)
469 bv->owner()->message(_("Running configure..."));
471 // Run configure in user lyx directory
474 one.startscript(Systemcall::Wait,
475 AddName(system_lyxdir, "configure"));
477 bv->owner()->message(_("Reloading configuration..."));
478 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
480 Alert::information(_("System reconfigured"),
481 _("The system has been reconfigured.\n"
482 "You need to restart LyX to make use of any \n"
483 "updated document class specifications."));